Python:转换日期时间格式

Python:转换日期时间格式

问题描述:

我有以下日期/时间格式的字符串:

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


2018-05-20T07:06:23.226

2018-05-20T07:06:23.226

我需要将其转换为以下格式:

I need to convert it to the following format:


2018-05-20 06:23 AM

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

我总是收到以下错误:


ValueError:时间数据日期与格式%Y-%m-%dT%H:%M:%S.%f不匹配

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


替换:

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

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

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