如何在Python中重新格式化时间戳

1 投票
3 回答
4829 浏览
提问于 2025-04-17 02:15

我有一些文本需要处理。现在的时间戳格式是先写日期,然后是数值。日期的格式是 yyyymmdd,我想把它改成 yyyy-mm-dd 或者其他格式,比如 yyyy/mm/dd 等等。我找不到可以在字符串中插入字符的方法,所以不太确定该怎么做。希望能得到一些高效的建议,关于如何在Python中切割和处理文本。谢谢!

19800101,0.76
19800102,0.00
19800103,0.51
19800104,0.00
19800105,1.52
19800106,2.54
19800107,0.00
19800108,0.00
19800109,0.00
19800110,0.76
19800111,0.25
19800112,0.00
19800113,6.10
19800114,0.00
19800115,0.00
19800116,2.03
19800117,0.00
19800118,0.00
19800119,0.25
19800120,0.25
19800121,0.00
19800122,0.00
19800123,0.00
19800124,0.00
19800125,0.00
19800126,0.00
19800127,0.00
19800128,0.00
19800129,0.00
19800130,7.11
19800131,0.25
19800201,.510
19800202,0.00
19800203,0.00
19800204,0.00

3 个回答

1

关于在Python中处理文本的一些通用建议

切片操作符:

str = '19800101,0.76'
print('{0}-{1}-{2}'.format(str[:4], str[4:6], str[6:]))

可以阅读:字符串(找一下关于切片的部分),以及字符串格式化

1

字符串是不可变的,也就是说你不能直接在字符串里插入字符。所以,如果你想在字符串中添加字符,这种方法是行不通的。你可以试试下面这个方法:

date = '19800131'
print '-'.join([date[:4],date[4:6],date[6:]])
3

我会这样做:

#!/usr/bin/env python

from datetime import datetime

with open("stuff.txt", "r") as f:
    for line in f:
        # Remove initial or ending whitespace (like line endings)
        line = line.strip()

        # Split the timestamp and value
        raw_timestamp, value = line.split(",")

        # Make the timestamp an actual datetime object
        timestamp = datetime.strptime(raw_timestamp, "%Y%m%d")

        # Print the timestamp separated by -'s. Replace - with / or whatever.
        print("%s,%s" % (timestamp.strftime("%Y-%m-%d"), value))

这样你就可以用 strftime 允许的任何格式来导入或打印时间戳了。

撰写回答