1

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.

StephenTG
  • 2,579
  • 6
  • 26
  • 36
Brana
  • 1,197
  • 3
  • 17
  • 38

4 Answers4

2

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
Martijn Pieters
  • 1,048,767
  • 296
  • 4,058
  • 3,343
1

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"
Raydel Miranda
  • 13,825
  • 3
  • 38
  • 60
1

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.

Andrew Clark
  • 202,379
  • 35
  • 273
  • 306
0

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
Anubhav Das
  • 940
  • 1
  • 11
  • 16