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
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
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