如何将此日期时间变量转换为 python 中与此格式等效的字符串?

How can this datetime variable be converted to the string equivalent of this format in python?

我正在使用 python 2.7.10

我有一个包含 2015-03-31 21:02:36.452000 的日期时间变量。我想将这个日期时间变量转换成一个看起来像 31-Mar-2015 21:02:36 的字符串。

如何在 python 2.7 中完成此操作?

使用 strptime 创建日期时间对象,然后使用 strftime 以您想要的方式对其进行格式化:

from datetime import datetime

s= "2015-05-31 21:02:36.452000"

print(datetime.strptime(s,"%Y-%m-%d %H:%M:%S.%f").strftime("%d-%b-%Y %H:%m:%S"))
31-May-2015 21:05:36

格式字符串如下:

%Y  Year with century as a decimal number.
%m  Month as a decimal number [01,12].    
%d  Day of the month as a decimal number [01,31].
%H  Hour (24-hour clock) as a decimal number [00,23]. 
%M  Minute as a decimal number [00,59].
%S  Second as a decimal number [00,61]. 
%f  Microsecond as a decimal number

在 strftime 中我们使用 %b,它是:

%b  Locale’s abbreviated month name.

显然我们只是忽略了输出字符串中的微秒。

如果您已经有日期时间对象,只需对日期时间对象调用 strftime:

print(dt.strftime("%d-%b-%Y %H:%m:%S"))