How to get month and year from date

Viewed 787

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?

2 Answers

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.

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.

Related