user2489252
user2489252

Reputation:

Looking for an easier way to parse a timestamp in Python

I am gathering data from an API that returns a timestamp in the following format: 'Thu May 22 15:40:24 +0000 2014', however, I need to convert it into a YYYY-MM-DD for my database. I wrote a function to do this, but it is quite ugly and I am wondering if someone tried to do this with some Python standard library module, e.g., datetime?

time = 'Thu May 22 15:40:24 +0000 2014'

def simplify_date(timestamp):
    """ 
    Converts a timestamp of the format
    'Thu May 22 15:40:24 +0000 2014' into a
    date string YYYY-MM-DD, e.g., '2014-05-22'.

    """
    months = {'Jan':'01', 'Feb':'02', 'Mar':'03',
              'Apr':'04', 'May':'05', 'Jun':'06',
              'Jul':'07', 'Aug':'08', 'Sep':'09',
              'Oct':'10', 'Nov':'11', 'Dec':'12'
              }
    t = timestamp.split()
    date = '%s-%s-%s' %(t[-1], months[t[1]], t[2])
    return date

print(simplify_date(time))
2014-05-22

Upvotes: 1

Views: 808

Answers (3)

Amber
Amber

Reputation: 527338

You can potentially use the datetime.datetime.strptime function to get a datetime object which can then be formatted via strftime to any format you want.

>>> ts = "Thu May 22 15:40:24 +0000 2014"
>>> dt = datetime.datetime.strptime(ts, "%a %b %d %H:%M:%S +0000 %Y")
>>> dt.strftime("%Y-%m-%d")
'2014-05-22'

However, there is a caveat that strptime doesn't handle timezone offsets well in Python 2. As long as the timezone is constant (+0000) you can just hard-code that into your format string. If you're using Python 3, you can use %z instead to match timezone offsets, but in Python 2 that won't work.

Also note that I've used %b above for the month - that matches on the short versions of month names. If the API actually returns the long version (hard to tell, since you used the one month that's never abbreviated in your example), you'll need %B instead.

Upvotes: 1

Tyler McAtee
Tyler McAtee

Reputation: 300

You are looking for the time.strftime function. You can find more information about this in the python documentation on strftime.

Upvotes: 0

abhishekgarg
abhishekgarg

Reputation: 1473

you can do something like this

import datetime

time = 'Thu May 22 15:40:24 +0000 2014'

new_time = datetime.datetime.strptime(time, "%a %b %d %H:%M:%S +0000 %Y")

print new_time.strftime("%Y-%d-%m")

Python Doc.

Upvotes: 1

Related Questions