简体   繁体   中英

How to change a datetime format in python?

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

As your error says what you give does not match format - %d-%m-%YT%H:%M:%S - means you are expecting after year: letter T hour : minutes : seconds when in example show it is hour u minutes m seconds s without T, so you should do:

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

Output:

2020-09-06 14:59:04

You need to always make sure that your desired date format should match up with your required format.

from datetime import datetime

date_object = datetime.strptime("06-09-202015u59m04s", '%d-%m-%Y%Hu%Mm%Ss')
print(date_object.strftime('%Y/%m/%d %H:%M:%S'))

Output

2020/09/06 15:59:04

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM