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

Question:

If I have lets say this string “2008-12-12 19:21:10” how can I convert it into a date and get the year, month and day from that created object separately?

Asked By: Ivan Juarez

||

Answers:

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
Answered By: Martijn Pieters

https://www.tutorialspoint.com/python/time_strptime.htm
Here you can find strptime() method complete description. where you can find all type of strings.
Eg:- To convert string like this ’15-MAY-12′

>>>from datetime import datetime
>>>datestring = "15-MAY-12"
>>>dt = datetime.strptime(datestring, '%d-%b-%Y')
>>>print(dt.year, dt.month, dt.day)
 2012 MAY 15
Answered By: user8217035

with milliseconds

>>> from datetime import datetime
>>> datestring = "2018-04-11 23:36:18.886585"
>>> dt = datetime.strptime(datestring, '%Y-%m-%d %H:%M:%S.%f')
>>> print dt.year, dt.month, dt.day
2018 04 11
Answered By: Vijay Krishna

One thing to add; pay attention that %y is for two digit year notation %Y is for the four digit one:

import datetime

datestring = '15-MAY-12'
print(datetime.datetime.strptime(datestring, '%d-%b-%y'))
>>> datetime.datetime(2012, 5, 15, 0, 0)

datestring = '15-MAY-2012'    
print(datetime.datetime.strptime(datestring, '%d-%b-%Y'))
>>> datetime.datetime(2012, 5, 15, 0, 0)
Answered By: Shivid
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.