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

时间:2015-05-31 13:10:46

标签: python python-2.7 datetime datetime-format

我正在使用python 2.7.10

我有一个包含2015-03-31 21:02:36.452000的日期时间变量。我想将此datetime变量转换为类似31-Mar-2015 21:02:36的字符串。

如何在python 2.7中完成?

1 个答案:

答案 0 :(得分: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"))
相关问题