1

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

2012-06-21 20:36:11

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

21st June 2012 20:36
4

2 回答 2

5
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
于 2012-06-22T01:00:26.770 回答
1

您想要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'
于 2012-06-22T00:56:35.503 回答