How to convert current date to epoch timestamp?

66

How to convert current date to epoch timestamp ?

Format current date:

29.08.2011 11:05:02

This question is tagged with python

~ Asked on 2011-08-30 09:29:35

The Best Answer is


101

That should do it

import time

date_time = '29.08.2011 11:05:02'
pattern = '%d.%m.%Y %H:%M:%S'
epoch = int(time.mktime(time.strptime(date_time, pattern)))
print epoch

~ Answered on 2011-08-30 09:36:30


20

Your code will behave strange if 'TZ' is not set properly, e.g. 'UTC' or 'Asia/Kolkata'

So, you need to do below

>>> import time, os
>>> d='2014-12-11 00:00:00'
>>> p='%Y-%m-%d %H:%M:%S'
>>> epoch = int(time.mktime(time.strptime(d,p)))
>>> epoch
1418236200
>>> os.environ['TZ']='UTC'
>>> epoch = int(time.mktime(time.strptime(d,p)))
>>> epoch
1418256000

~ Answered on 2015-01-06 09:06:13


Most Viewed Questions: