Python 从日期时间数据获取日期

Python 从日期时间数据获取日期,python,datetime,Python,Datetime,我有一个这种格式的日期时间数据 08:15:54:012 12 03 2016 +0000 GMT+00:00 我只需要提取日期,即python中的12 03 2016 我试过了 datetime_object=datetime.strptime('08:15:54:012 12 03 2016 +0000 GMT+00:00','%H:%M:%S:%f %d %m %Y') 我得到一份工作 ValueError: unconverted data remains: +0000 GMT+0

我有一个这种格式的日期时间数据

08:15:54:012 12 03 2016 +0000 GMT+00:00
我只需要提取日期,即python中的
12 03 2016

我试过了

datetime_object=datetime.strptime('08:15:54:012 12 03 2016 +0000 GMT+00:00','%H:%M:%S:%f %d %m %Y')
我得到一份工作

ValueError: unconverted data remains:  +0000 GMT+00:00

如果您不介意使用外部库,我发现它比pythons内部datetime更直观。只要你这么做,它几乎可以解析任何东西

>>> import dateparser
>>> dateparser.parse('08:15:54:012 12 03 2016 +0000 GMT+00:00')

它声称它可以处理时区偏移,尽管我还没有测试过它

如果需要将其作为字符串,则使用切片

text = '08:15:54:012 12 03 2016 +0000 GMT+00:00'

print(text[13:23])

# 12 03 2016
但您也可以转换为datetime

from datetime import datetime

text = '08:15:54:012 12 03 2016 +0000 GMT+00:00'

datetime_object = datetime.strptime(text[13:23],'%d %m %Y')

print(datetime_object)
# datetime.datetime(2016, 3, 12, 0, 0)

顺便说一句:

在您的原始版本中,您必须删除
+0000 GMT+00:00
使用切片
[:-16]

strptime('08:15:54:012 12 03 2016 +0000 GMT+00:00'[:-16], '%H:%M:%S:%f %d %m %Y')

您还可以使用
split()
join()


您可以这样做:

d = '08:15:54:012 12 03 2016 +0000 GMT+00:00'
d = d[:23] #Remove the timezone details

from datetime import datetime
d = datetime.strptime(d, "%H:%M:%S:%f %m %d %Y") #parse the string
d.strftime('%m %d %Y') #format the string
你会得到:

'12 03 2016'

如果需要将其作为字符串,请使用切片
[13:23]
-
'08:15:54:012 12 03 2016+0000 GMT+00:00'[13:23]
'12 03 2016'