在python中格式化日期戳

ing*_*.am 1 python format datetime timestamp date

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

2012-06-21 20:36:11
Run Code Online (Sandbox Code Playgroud)

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

21st June 2012 20:36
Run Code Online (Sandbox Code Playgroud)

Hug*_*ell 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)
Run Code Online (Sandbox Code Playgroud)

回报

21 June 2012 20:36
Run Code Online (Sandbox Code Playgroud)

如果你真的想要'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)
Run Code Online (Sandbox Code Playgroud)

得到你

21st June 2012 20:36
Run Code Online (Sandbox Code Playgroud)