How can I convert a string into a date object and get year, month and day separately?

Use the datetime.datetime.strptime() function:

from datetime import datetime
dt = datetime.strptime(datestring, '%Y-%m-%d %H:%M:%S')

Now you have a datetime.datetime object, and it has .year, .month and .day attributes:

>>> from datetime import datetime
>>> datestring = "2008-12-12 19:21:10"
>>> dt = datetime.strptime(datestring, '%Y-%m-%d %H:%M:%S')
>>> print dt.year, dt.month, dt.day
2008 12 12

Leave a Comment

tech