简体   繁体   中英

How to convert this format to datetime in Python

My data is in this format Feb 1, 2021 @ 01:22:01.602, I am using this to convert it to datetime:

datetime.datetime.strptime(str(01:22:01.602), '%H:%M:%S.%f')

Gives me the error: ValueError:'object' did not match format '%H:%M:%S.%f'

Something like this:

>>> from datetime import datetime
>>> date_string = 'Feb 1, 2021 @ 01:22:01.602'
>>> datetime_obj = datetime.strptime(date_string,'%b %d, %Y @ %H:%M:%S.%f')
>>> datetime_obj
datetime.datetime(2021, 2, 1, 1, 22, 1, 602000)

The following would help you:

import datetime

date_in_special_format="Feb 1, 2021 @ 01:22:01.602"
merkki=date_in_special_format.index('@')
time_in_special_format=date_in_special_format[merkki+2:len(date_in_special_format)]

clocktime=datetime.datetime.strptime(time_in_special_format, '%H:%M:%S.%f').strftime('%H:%M:%S.%f')

print(clocktime)

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