2

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?

10 Rep
  • 2,217
  • 7
  • 19
  • 33
shekwo
  • 1,411
  • 1
  • 20
  • 50

2 Answers2

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
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
  • This ignores the timezone. – Bertrand Marron May 08 '20 at 19:02
  • @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