使用Python将字符串转换为格式化的日期时间字符串

yipeiwu_com6年前Python基础

我正在尝试将字符串“20091229050936”转换为“2009年12月29日(UTC)”

>>>import time
>>>s = time.strptime("20091229050936", "%Y%m%d%H%M%S")
>>>print s.strftime('%H:%M %d %B %Y (UTC)')

给 AttributeError: 'time.struct_time' object has no attribute 'strftime'

显然,我犯了一个错误:时间错了,它是一个日期时间对象!它有一个日期和时间组件!

>>>import datetime
>>>s = datetime.strptime("20091229050936", "%Y%m%d%H%M%S")

给 AttributeError: 'module' object has no attribute 'strptime'

我是怎么意思将字符串转换为格式化的日期字符串?

解决方案

time.strptime返回time_struct; time.strftime接受a time_struct作为可选参数:

>>>s = time.strptime(page.editTime(), "%Y%m%d%H%M%S")
>>>print time.strftime('%H:%M %d %B %Y (UTC)', s)
给 05:09 29 December 2009 (UTC)

总结

以上所述是小编给大家介绍的使用Python将字符串转换为格式化的日期时间字符串,希望对大家有所帮助,如果大家有任何疑问欢迎给我留言,小编会及时回复大家的!

相关文章

centos6.5安装python3.7.1之后无法使用pip的解决方案

编译安装全是坑…… 第一遍装完无法使用pip,报错找不到ssl模块。各种报错: pip is configured with locations that require TLS/SS...

python进阶教程之函数对象(函数也是对象)

秉承着一切皆对象的理念,我们再次回头来看函数(function)。函数也是一个对象,具有属性(可以使用dir()查询)。作为对象,它还可以赋值给其它对象名,或者作为参数传递。 lambd...

python实现翻转棋游戏(othello)

python实现翻转棋游戏(othello)

利用上一篇的框架,再写了个翻转棋的程序,为了调试minimax算法,花了两天的时间。 几点改进说明: 拆分成四个文件:board.py,player.py,ai.py,othell...

django 控制页面跳转的例子

如下所示: def delEquipment(request, delip): print delip ip=delip conn= MySQLdb.connect(...

Python+selenium点击网页上指定坐标的实例

Python+selenium点击网页上指定坐标的实例

例如有些页面元素很难获取,但是位置很固定,那么可以直接用坐标来进行操作 例如要对页面上的(x:200, y:100)进行操作,可以用如下代码: from selenium impor...