Search code examples
pythondatetimestrptimestring-conversion

Formatting a strptime value from a string as a date


I have the following code which is the beginnings of reading in a text file, turning it into a json object, then grabbing some of the values within it and manipulating the date string read in:

    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

Some sample output:

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)]
...
...
...

Can anyone tell me the bit I am missing to get the second element of the list into the correct format?

Thanks


Solution

  • I guess '2015-08-08 00:00:00' is what you mean by "correct format". If so:

    >>> 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'
    

    An object when printed as an element in a container is printed by calling its __repr__, not __str__, which is why your datetime objects do not appear to be formatted in a list. See this:

    >>> 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']
    

    EDIT:

    Now given your list printing code, it's in fact quite easy. Just change it to:

    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]
    

    Or equivalently:

    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
    

    It seems that you are not familiar with list comprehension and map. Read about them here and here.