将字符串中的strptime值格式化为日期

时间:2016-02-24 00:33:02

标签: python datetime strptime string-conversion

我有以下代码,它是在文本文件中读取的开始,将其转换为json对象,然后获取其中的一些值并操作读入的日期字符串:

    import json
    from datetime import date, timedelta, datetime

    my_list = []
    my_list2 = []

    filepath = 'myfile'
    x_contents = open(filepath, "r")
    x_contents = x_contents.read()
    x_contents = json.loads(x_contents.replace("u'", '"').replace("'", '"'))

    for mydate in x_contents:

        for mydate2 in mydate:

            the_match = mydate2[0]
            the_date = mydate2[2]
            the_date = datetime.strptime(the_date,"%A, %b %d %Y")
            print the_date #writes to the log in the correct format

            my_list.append(the_match)
            my_list.append(the_date) #appends the strptime tuple to the list, not the formatted date as it appears with the print statement above

            my_list2.append(my_list)
            my_list = []

for i in my_list2:

    print i

一些示例输出:

2015-08-08 00:00:00
2015-08-08 00:00:00
2015-08-08 00:00:00
2015-08-08 00:00:00
2015-08-08 00:00:00
...
...
...
[958431, datetime.datetime(2015, 8, 8, 0, 0)]
[958427, datetime.datetime(2015, 8, 8, 0, 0)]
[958429, datetime.datetime(2015, 8, 8, 0, 0)]
[958430, datetime.datetime(2015, 8, 8, 0, 0)]
[958433, datetime.datetime(2015, 8, 8, 0, 0)]
...
...
...

任何人都可以告诉我我缺少的一点是为了让列表的第二个元素变成正确的格式吗?

由于

2 个答案:

答案 0 :(得分:1)

我猜'2015-08-08 00:00:00'就是“正确格式”的含义。如果是这样的话:

>>> import datetime
>>> t = datetime.datetime(2015, 8, 8, 0, 0)
>>> t
datetime.datetime(2015, 8, 8, 0, 0)
>>> str(t)
'2015-08-08 00:00:00'

通过调用__repr__而非__str__来打印作为容器中的元素打印的对象,这就是为什么您的datetime对象似乎没有在列表中格式化的原因。见:

>>> repr(t)
'datetime.datetime(2015, 8, 8, 0, 0)'
>>> [t, str(t)]
[datetime.datetime(2015, 8, 8, 0, 0), '2015-08-08 00:00:00']

编辑:

现在给出你的列表打印代码,实际上很容易。只需将其更改为:

for i in my_list2:
    # instead of i, print a list in which every item in i is converted to str(i)
    print [str(item) for item in i]

或等效地:

for i in my_list2:
    # map(str, i) does the same thing as [str(item) for item in i]
    print map(str, i)  # would have to be list(map(str, i)) in python 3

您似乎不熟悉列表理解和map。了解他们herehere

答案 1 :(得分:1)

我认为你应该使用

datetime.datetime.strftime(the_date, "%x %X") 

(或其他一些格式字符串)以您希望的方式格式化日期时间。请查看strftime以获取更多指导。