Datetime object

710 Views Asked by At

How do I get the year and month from a datetime.datetime object? Here is the code I have problems with:

w = whois.whois('http://stackoverflow.com')
datatime = w.expiration_date
print datatime

the printed object is:

[datetime.datetime(2015, 12, 26, 0, 0), u'2015-12-26T19:18:07-07:00']

How do I get year, month, and day from the part datetime.datetime(2015, 12, 26, 0, 0). I guess I could use regex, but there must be a better way to do this.

4

There are 4 best solutions below

0
Martijn Pieters On

It's a list object with one datetime object in it, plus an ISO 8601 string. Just use attributes on the first object:

datatime[0].year
datatime[0].month
datatime[0].day

Demo:

>>> datatime
[datetime.datetime(2015, 12, 26, 0, 0), u'2015-12-26T19:18:07-07:00']
>>> datatime[0]
datetime.datetime(2015, 12, 26, 0, 0)
>>> datatime[0].year
2015
>>> datatime[0].month
12
>>> datatime[0].day
26
1
Raydel Miranda On

Datetime objects has month, year and day attributes.

 now = datetime.datetime.now()
 print(now.day)
 print(now.month)
 print(now.year)

You can use calendar for get the month name:

import calendar
calendar.month_name[datetime.datetime.now().month]  # Output "April"
0
Andrew Clark On

Here is how you can get those fields separately as integers:

>>> import datetime
>>> dt = datetime.datetime(2015, 12, 26, 0, 0)
>>> dt.year
2015
>>> dt.month
12
>>> dt.day
26

Or if you want to format just those fields into a string you can use strftime() for example:

>>> dt.strftime('%Y-%m-%d')
'2015-12-26'

In this case it looks like your datatime object is actually a two element list, with a datetime object as the first element and string as the second element. So to get to the datetime object you would just use datatime[0] in place of the dt in my example code.

0
Anubhav Das On

For anyone looking for this now, here's an updated answer for Python 3.7.4 with time information:

>>> datatime
datetime.datetime(2020, 2, 2, 11, 59, 59)
>>> print(datatime)
2020-02-02 11:59:59
>>> datatime.year
2020
>>> datatime.month
2
>>> datatime.day
2
>>> datatime.hour
11
>>> datatime.minute
59
>>> datatime.second
59
>>> datatime.microsecond
0