Reputation: 135
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'
Upvotes: 2
Views: 9827
Reputation: 665
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
Upvotes: 1
Reputation: 604
>>> 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'
Upvotes: 4
Reputation: 36735
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
uminutes
mseconds
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
Upvotes: 2