【问题标题】:How do I convert `str` object to `datetime` object in python [duplicate]如何在python中将`str`对象转换为`datetime`对象[重复]
【发布时间】:2019-11-01 16:15:30
【问题描述】:

我有一个这种格式的字符串:2019-06-18T11:00:10.499378622Z。我正在尝试将其转换为日期时间对象。

我试过了

s_datetime = datetime.strptime(s_datetime_string, '%Y-%m-%d*%H:%M:%S*')
import datetime.datetime
s_datetime = datetime.strptime(s_datetime_string, '%Y-%m-%d*%H:%M:%S*')

Getting ValueError as the regex does not match

【问题讨论】:

  • 强烈推荐箭头包作为日期时间的替代品。

标签: python python-3.x time


【解决方案1】:

我也遇到了这个错误,所以我在处理 ISO 时间时创建了一个小函数。

def ISOtstr(iso):

    dcomponents = [1,1,1]
    dcomponents[0] = iso[:4]
    dcomponents[1] = iso[5:7]
    dcomponents[2] = iso[8:10]
    tcomponents = [1,1,1]
    tcomponents[0] = iso[11:13]
    tcomponents[1] = iso[14:16]
    tcomponents[2] = iso[17:19]
    d = dcomponents
    t = tcomponents
    string = "{}-{}-{} {}:{}:{}".format(d[0],d[1],d[2],t[0],t[1],t[2])
    return string

将您的 ISO 转换为字符串:

string = '2019-06-18T11:00:10.499378622Z'
date_string = ISOtstring(string)
date_obj = datetime.datetime.strptime(date_string, '%Y-%m-%d %H:%M:%S')
#Output
#datetime.datetime(2019, 6, 18, 11, 0, 10)

很可能有更好的方法来做到这一点。但我在处理 ISO 字符串时使用它。

如果你经常使用它,你可以把它作为一个单独的函数:

def ISOtdatetime(iso):
  date_string = ISOtstring(iso)
  date_obj = datetime.datetime.strptime(date_string, '%Y-%m-%d %H:%M:%S')
  return date_obj

刚意识到我在第一次创建函数时有一些毫无意义的代码。它们已被删除。

【讨论】:

  • 非常感谢,你拯救了我的一天@jedkea!
【解决方案2】:

您的输入也有错误,尤其是在 second 单元上。但是,当我稍微更改您的second 单位时,它就起作用了。所以,我对此一无所知。

from datetime import datetime

s_datetime = datetime.strptime('2019-06-18T11:00:10.499378Z', '%Y-%m-%dT%H:%M:%S.%fZ')
print(s_datetime)
print(type(s_datetime))

输出:

2019-06-18 11:00:10.499378
<class 'datetime.datetime'>

【讨论】:

  • 我仍然遇到问题:/`ValueError:时间数据'2019-06-18T15:08:46.131737185Z'与格式'%Y-%m-%dT%H不匹配: %M:%S.%fZ'
猜你喜欢
  • 2023-03-27
  • 1970-01-01
  • 1970-01-01
  • 2011-09-21
  • 1970-01-01
  • 1970-01-01
  • 2015-11-14
  • 2019-06-28
  • 2015-11-26
相关资源
最近更新 更多