加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Python > 正文

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

发布时间:2020-12-20 11:43:19 所属栏目:Python 来源:网络整理
导读:我使用的是 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以
我使用的是 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"))

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读