如何在python中将此datetime变量转换为等效于此格式的字符串?

我使用的是
python 2.7.10

我有一个datetime变量,其中包含2015-03-31 21:02:36.452000.我想将此datetime变量转换为一个看起来像31-Mar-2015 21:02:36的字符串.

怎么能在python 2.7中完成?

最佳答案 使用strptime创建一个datetime对象,然后使用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.

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

如果你已经有一个datetime对象,只需在datetime对象上调用strftime:

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