简体   繁体   中英

Python: convert datetime format

I've a string in the following date/time format:

2018-05-20T07:06:23.226

I need to convert it to the following format:

2018-05-20 06:23 AM

I tried the following code, but I'm surely making some mistake here:

date = "2018-05-20T07:06:23.226"
d = datetime.datetime.strptime('date', '%Y-%m-%dT%H:%M:%S.%f')
new_date = d.strftime('%y-%m-%d %H:%M %p')

I always get the following error:

ValueError: time data 'date' does not match format '%Y-%m-%dT%H:%M:%S.%f'

replace:

d = datetime.datetime.strptime('date', '%Y-%m-%dT%H:%M:%S.%f')

with

d = datetime.datetime.strptime(date, '%Y-%m-%dT%H:%M:%S.%f')

Also

new_date = d.strftime('%y-%m-%d %H:%M %p')

with

new_date = d.strftime('%Y-%m-%d %I:%M %p')

If you wish to use variable inside string, you can do it since Python 3.6:

date = "2018-05-20T07:06:23.226"
d = datetime.datetime.strptime(f'{date}', '%Y-%m-%dT%H:%M:%S.%f')
new_date = d.strftime('%y-%m-%d %H:%M %p')

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