Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/342.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
在python中,如何将此datetime变量转换为与此格式等效的字符串?_Python_Python 2.7_Datetime_Datetime Format - Fatal编程技术网

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

在python中,如何将此datetime变量转换为与此格式等效的字符串?,python,python-2.7,datetime,datetime-format,Python,Python 2.7,Datetime,Datetime Format,我正在使用python 2.7.10 我有一个datetime变量,它包含2015-03-31 21:02:36.452000。我想将这个datetime变量转换成一个字符串,看起来像2015年3月31日21:02:36 在python 2.7中如何实现这一点?使用strtime创建datetime对象,然后使用strftime按照您想要的方式对其进行格式化: from datetime import datetime s= "2015-05-31 21:02:36.452000" prin

我正在使用python 2.7.10

我有一个datetime变量,它包含
2015-03-31 21:02:36.452000
。我想将这个datetime变量转换成一个字符串,看起来像
2015年3月31日21:02:36


在python 2.7中如何实现这一点?

使用strtime创建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"))
一次快速的旅行会给你一个去哪里找的提示。