python中的日期转换

时间:2011-07-03 19:18:02

标签: python date

我在文本文件中有一些数据,格式如下:

50 Cent     1975-07-06
75 Cents    1933-01-29
9th Wonder  1975-01-15
A Fine Frenzy   1984-12-23

我想将其转换为:

50 Cent     July 6, 1975
75 Cents    January 29, 1933
9th Wonder  January 15, 1975
A Fine Frenzy   December 23, 1984

你们中的任何人都可以帮助我。谢谢你们!

3 个答案:

答案 0 :(得分:3)

import time

text = """50 Cent     1975-07-06
75 Cents    1933-01-29
9th Wonder  1975-01-15
A Fine Frenzy   1984-12-23"""

for line in text.splitlines():
    dob = line.rsplit(None, 1)[-1]
    dob_new = time.strftime('%B %d, %Y', time.strptime(dob, '%Y-%m-%d'))

    print line.replace(dob, dob_new)

<强>结果:

50 Cent     July 06, 1975
75 Cents    January 29, 1933
9th Wonder  January 15, 1975
A Fine Frenzy   December 23, 1984

<强>加成:

A strftime cheatsheet

答案 1 :(得分:3)

您可以使用strftime and strptime from datetime module 请在下面找到我的示例代码:

output = []
with open(filename, 'r') as f:
    for line in (l.strip() for l in f if l.strip()):
        data = line.split()
        output.append(line.replace(data[-1], datetime.strptime(data[-1],'%Y-%m-%d').strftime('%B %d, %Y')))

答案 2 :(得分:1)

一种方法是使用time.strptime进行解析,使用time.strftime进行格式化。 pydoc time用于文档。