问题描述:

i get from the api following string for date and time

t = "2015-02-06T10:11:02.900Z"

I need only the date in this format: DD.MM.YYYY

This is what i tried:

from datetime import datetime

datetime.strptime(t, "%Y-%m-%dT%H:%M:%S.%f%z")

And this is the error i get:

ValueError: time data '2015-02-06T10:11:02.900Z' does not match format '%Y-%m-%dT%H:%M:%S.%f%z'

网友答案:

Take only the date part of the string:

>>> datetime.strptime(t.split('T')[0], "%Y-%m-%d")
datetime.datetime(2015, 2, 6, 0, 0)

To get DD.MM.YYYY format result, use datetime.strftime:

>>> datetime.strptime(t.split('T')[0], "%Y-%m-%d").strftime('%d.%m.%Y')
'06.02.2015'
网友答案:

You've used the incorrect directive: '%z' doesn't match Z ('%z' matches a numeric utc offset such as '+0200'). See How to parse ISO formatted date in python? Just replace %z with Z in your case:

>>> from datetime import datetime
>>> d = datetime.strptime("2015-02-06T10:11:02.900Z", "%Y-%m-%dT%H:%M:%S.%fZ")
>>> d
datetime.datetime(2015, 2, 6, 10, 11, 2, 900000)

To get DD.MM.YYYY, you could use .strftime() method. See Convert datetime object to a String of date only in Python:

>>> d.strftime('%d.%m.%Y')
'06.02.2015'
相关阅读:
Top