如何将 str('2018-12-02T14:29:41.655+05:30') 转换为日期和时间?


date_object = datetime.strptime(one_bike.iloc[0,1], '%Y-%m-%dT%H:%M:%S+05:30').date()

预期成果:

Date - '%Y-%m-%d'
Time - '%H:%M:%S'

从你的标题中我们可以假设one_bike.iloc[0,1]里面有str('2018-12-02T14:29:41.655+05:30')

代码不起作用的原因是您错过了毫秒。 您可以使用%S.%f添加它 所以代码应该看起来像

date_object = datetime.strptime(str('2018-12-02T14:29:41.655+05:30'), '%Y-%m-%dT%H:%M:%S.%f+05:30').date()

strptime(( 类方法有两个参数:

  • 字符串(转换为日期时间(
  • 格式代码

考虑到您尝试转换的日期字符串是"2018-12-02T14:29:41.655+05:30"。

此字符串采用"Year-Month-DayThh:mm::ss.ms+05:30"的格式。因此,您编写的格式字符串缺少微秒指令 (%f(。

from datetime import datetime
date_string = "2018-12-02T14:29:41.655+05:30"
date_object = datetime.strptime(date_string, '%Y-%m-%dT%H:%M:%S.%f+05:30').date()
print ("date_object =", date_object)
print("type of date_object =", type(date_object))

Python strptime(( 对此有一个非常好的参考文档。

最新更新