Biswajit Chopdar
Biswajit Chopdar

Reputation: 871

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'

Upvotes: 1

Views: 14902

Answers (2)

Haleemur Ali
Haleemur Ali

Reputation: 28233

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

Upvotes: 7

zipa
zipa

Reputation: 27869

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

Upvotes: 1

Related Questions