How to change a datetime format in python?

Issue

How can one make 2020/09/06 15:59:04 out of 06-09-202015u59m04s.

This is my code:

my_time = '06-09-202014u59m04s'
date_object = datetime.datetime.strptime(my_time, '%d-%m-%YT%H:%M:%S')
print(date_object)

This is the error I receive:

ValueError: time data '06-09-202014u59m04s' does not match format '%d-%m-%YT%H:%M:%S'

Solution

>>> from datetime import datetime
>>> my_time = '06-09-202014u59m04s'
>>> dt_obj = datetime.strptime(my_time,'%d-%m-%Y%Hu%Mm%Ss')

Now you need to do some format changes to get the answer as the datetime object always prints itself with : so you can do any one of the following:

Either get a new format using strftime:

>>> dt_obj.strftime('%Y/%m/%d %H:%M:%S')
'2020/09/06 14:59:04'  

Or you can simply use .replace() by converting datetime object to str:

>>> str(dt_obj).replace('-','/')
'2020/09/06 14:59:04'

Answered By – JenilDave

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published