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 に答える