转换为缺少的加号偏移量datetime字符串为正确的datetime

用户名

通常,我会收到这种格式的datetime字符串,d_string = '2019-03-25 15:30:00+00:00'并且可以使用转换为正确的datetime

date_converted = datetime.strptime(d_string , '%Y-%m-%d %H:%M:%S%z')

但是有时候,我收到这样的日期字符串'2019-03-25 15:30:00 00:00'plus不再有任何符号。如何将这种类型的日期字符串验证为正确的datetime格式?我总是可以从日期字符串的最后第4个位置添加加号并进行验证,但这并不是更好的解决方案。

有没有更好的办法 ?

阿兹罗

如果您想00:00在末尾使用,可以添加+来匹配所需的模式,这是您可以执行的操作

if re.fullmatch(r"[\d-]{10} [\d:]{8} [\d:]{5}", value):
    value = re.sub(r"(?<=[\d:]{8})( )(?=[\d:]{5})", "+", value)

给予

values = ['2019-03-25 15:30:00+00:00', '2019-03-25 15:30:00 00:00']
for value in values:
    if re.fullmatch(r"[\d-]{10} [\d:]{8} [\d:]{5}", value):
        value = re.sub(r"(?<=[\d:]{8})( )(?=[\d:]{5})", "+", value)
    date_converted = datetime.strptime(value, '%Y-%m-%d %H:%M:%S%z')
    print(date_converted)

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章

使用正确的偏移量将UTC DateTime转换为EST DateTime

在PHP中发生了字符串偏移量强制转换的正确解决方案

将时区pytz字符串转换为python / django中的偏移量

将具有UTC偏移量的字符串转换为日期时间对象

将时区字符串(即美国/东部)转换为偏移量

使用偏移量将字符串日期转换为DateTimePST(String)和DateTimeLocal(String)?

熊猫数据帧日期时间 - 将字符串转换为日期时间偏移量

如何使用UTC偏移量转换字符串

将DateTimeOffset转换为DateTime并向此DateTime添加偏移量

将带有偏移量的日期字符串转换为忽略偏移量的自定义格式

Java将ISO 8601字符串转换为日期,忽略偏移量

接收包括字符串的时区偏移量的日期,并使用该时区转换为其他格式

boost spirit X3解析器,可将偏移量转换为原始字符串

在bash Shell脚本中将带有偏移量字符串的GMT转换为MST

将datetime.min转换为偏移量知道的日期时间

使用strptime将带有偏移量的时间戳转换为datetime obj

如何将日期,时间和UTC偏移量转换为本地DateTime

C# - .net core DateTime 转换为 UTC 分钟偏移量

对象转换为 Json 字符串并转换回对象失败,缺少 DateTime 元素 Android

无法正确使用字符串偏移量作为数组

将datetime转换为string始终默认为系统时区偏移量,需要在结果中获取用户的时区偏移量

javascript datetime转换为字符串并返回datetime?

AngularJs将字符串datetime转换为datetime对象

Python使用时区偏移量转换日期/时间字符串

非法字符串偏移量未定义偏移量:2

警告:输入中的字符串偏移量'id'为非法

如何将格式为 'YYYY-DD-MM HH:MI:SS.MS +00:00' 的字符串(其中最后四个字符是时区偏移量)转换为 postgres timestamptz?

在字符串中查找元素的偏移量

如何忽略字符串日期时间的偏移量