turtle
turtle

Reputation: 8093

Convert string to epoch timestamp

I have timestamps in the following format:

date = Fri Nov 30 13:32:45 UTC 2012

Is there a way to convert this string to an epoch timestamp? I haven't been able to figure out how to convert this string? Here's what I have been trying:

import datetime

d = 'Fri Nov 30 13:32:45 UTC 2012'
fmt = '%a %b %e %R %Y'
print d.strftime(fmt)

Upvotes: 1

Views: 481

Answers (2)

Serge Ballesta
Serge Ballesta

Reputation: 149075

You need strptime method of class datetime. And the format you need is %a %b %d %H:%M:%S %Z %Y. With your example it give :

>>> import datetime
>>> date = "Fri Nov 30 13:32:45 UTC 2012"
>>> fmt = "%a %b %d %H:%M:%S %Z %Y"
>>> d = datetime.datetime.strptime(date, fmt)
>>> d
datetime.datetime(2012, 11, 30, 13, 32, 45)
>>> d.timestamp()
1354278765.0

Upvotes: 0

Stéphane Bruckert
Stéphane Bruckert

Reputation: 22933

You missed the timezone directive:

%Z Time zone name (no characters if no time zone exists).

You used the wrong "day of the month" directive:

%d Day of the month as a decimal number [01,31].

You used the wrong "time" directive:

%X Locale’s appropriate time representation.

Try:

>>> import time
>>> d = 'Fri Nov 30 13:32:45 UTC 2012'
>>> fmt = '%a %b %d %X %Z %Y'
>>> epoch = int(time.mktime(time.strptime(d, fmt)))
>>> print epoch
1354278765

Upvotes: 2

Related Questions