I have a date in this format - 2020-01-31T00:00:00.000Z
, this is coming from an API. How do I get the month (e.g. April) and year (e.g. 2020) from this date using the datetime module?
Asked
Active
Viewed 1,240 times
2
2 Answers
2
I would suggest you to use the dateutil
package to parse ISO 8601 dates.
>>> from dateutil import parser
>>> parser.isoparse('2020-01-31T00:00:00.000Z')
datetime.datetime(2020, 1, 31, 0, 0, tzinfo=tzutc())
Then you can retrieve the month and year from the datetime
object it returns.

Bertrand Marron
- 21,501
- 8
- 58
- 94
-
Thank you! Solved it – shekwo May 08 '20 at 19:04
1
If you want to do using datetime module you can do this as
from datetime import datetime
input_dt = '2020-01-31T00:00:00.000Z'
dt_object = datetime.strptime(input_dt, "%Y-%m-%dT%H:%M:%S.%fz")
Now you can do
dt_object.year
dt_object.day
dt_object.month
The strptime() method creates a datetime object from the given string.

tausif
- 672
- 1
- 6
- 15
-
-
@BertrandMarron "When the %z directive is provided to the strptime() method, an aware datetime object will be produced. The tzinfo of the result will be set to a timezone instance." as it says here https://stackoverflow.com/questions/3305413/python-strptime-and-timezones – tausif May 08 '20 at 19:09
-
Your code will not work with `2020-01-31T00:00:00.000+04:00`, for instance. – Bertrand Marron May 08 '20 at 19:20