- The function
datetime.datetime.now()
returned datetime string format is ( yyyy, month, day, hour, minute, second, millisecond ).
>>> datetime.datetime.now()
datetime.datetime(2021, 4, 5, 19, 59, 10, 165964)
- We can use the python function
strftime()
to convert the datetime value to the formatted string that we want.
>>> curr_time = datetime.datetime.now()
>>>
>>> curr_time.strftime("%Y-%m-%d")
'2021-04-05'
>>>
>>> curr_time.strftime("%m/%d")
'04/05'
- Convert python datetime value to string example.
>>> curr_time = datetime.datetime.now()
>>>
>>> datetime.datetime.strftime(curr_time,'%Y-%m-%d %H:%M:%S')
'2021-04-05 20:05:33'
- Convert python datetime string to datetime example.
>>> import datetime
>>>
>>> time_str = '2021-06-06 15:59:58'
>>>
>>> datetime.datetime.strptime(time_str,'%Y-%m-%d %H:%M:%S')
datetime.datetime(2021, 6, 6, 15, 59, 58)
>>>