python中的日期转换

2024-09-28 22:35:40 发布

您现在位置:Python中文网/ 问答频道 /正文

我在以下格式的文本文件中有一些数据:

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

我想把它转换成:

^{pr2}$

你们谁能帮忙吗我。谢谢提前!在


Tags: 数据格式centwonder文本文件finepr2cents
3条回答

一种方法是使用时间.strptime解析和时间.strftime格式化。pydoc time获取文档。在

您可以使用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')))
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)

结果:

^{pr2}$

奖金:

A strftime cheatsheet

相关问题 更多 >