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

时间:2011-09-14 03:47:24

标签: python string parsing text methods

我有一些需要处理的文字。目前列出时间戳,然后列出值。时间戳的格式为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 个答案:

答案 0 :(得分: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允许的任何格式导入或打印时间戳。

答案 1 :(得分:1)

  

关于在python中切片和切块文本的一般建议

切片运算符:

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

阅读:strings(在切片上查找部分)和string formatting

答案 2 :(得分:1)

字符串不可变,因此将字符插入字符串将不起作用。试试这个:

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