【问题标题】:Format datestamp in python在python中格式化时间戳
【发布时间】:2012-06-24 07:43:33
【问题描述】:

在python中使用import datetime,是否可以采用格式化的时间/日期字符串,例如:

2012-06-21 20:36:11

并将其转换为一个对象,然后我可以使用该对象来生成一个新格式化的字符串,例如:

21st June 2012 20:36

【问题讨论】:

标签: python datetime date format timestamp


【解决方案1】:
import time

s = '2012-06-21 20:36:11'

t = time.strptime(s, '%Y-%m-%d %H:%M:%S')
print time.strftime('%d %B %Y %H:%M', t)

返回

21 June 2012 20:36

如果你真的想要'st',

def nth(n):
    return str(n) + nth.ext[int(n)%10]
nth.ext = ['th', 'st', 'nd', 'rd'] + ['th']*6

print nth(t.tm_mday) + time.strftime(' %B %Y %H:%M', t)

得到你

21st June 2012 20:36

【讨论】:

  • +1 是一个不错的解决方案。我也喜欢在函数对象中为函数塞入私有变量的技巧,就像你对 nth.ext 所做的那样;我也这样做。
【解决方案2】:

你想要datetime.strptime,它将文本解析为日期时间:

>>> d = "2012-06-21 20:36:11"
>>> datetime.datetime.strptime(d, "%Y-%m-%d %H:%M:%S")
datetime.datetime(2012, 6, 21, 20, 36, 11)

以您想要的方式格式化日期几乎是可行的:

>>> datetime.datetime.strftime(t, "%d %B %Y %H:%m")
'21 June 2012 20:06'

【讨论】:

    猜你喜欢
    • 2019-02-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-07-09
    • 1970-01-01
    相关资源
    最近更新 更多