69

How to convert current date to epoch timestamp ?

Format current date:

29.08.2011 11:05:02
Bdfy
  • 23,141
  • 55
  • 131
  • 179

9 Answers9

108

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
Pierre Lacave
  • 2,608
  • 2
  • 19
  • 28
23

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
OneCricketeer
  • 179,855
  • 19
  • 132
  • 245
Mohammad Shahid Siddiqui
  • 3,730
  • 2
  • 27
  • 12
14

Assuming you are using a 24 hour time format:

import time;
t = time.mktime(time.strptime("29.08.2011 11:05:02", "%d.%m.%Y %H:%M:%S"));
Paul
  • 139,544
  • 27
  • 275
  • 264
6
import time
def expires():
    '''return a UNIX style timestamp representing 5 minutes from now'''
    return int(time.time()+300)
Mal
  • 533
  • 1
  • 12
  • 27
4

if you want UTC try some of the gm functions:

import time
import calendar

date_time = '29.08.2011 11:05:02'
pattern = '%d.%m.%Y %H:%M:%S'
utc_epoch = calendar.timegm(time.strptime(date_time, pattern))
print utc_epoch
Kevin Kreiser
  • 594
  • 5
  • 11
4
from time import time
>>> int(time())
1542449530


>>> time()
1542449527.6991141
>>> int(time())
1542449530
>>> str(time()).replace(".","")
'154244967282'

But Should it not return ?

'15424495276991141'
aks
  • 554
  • 6
  • 8
  • 1
    time.time() returns current seconds after epoch (posix time) as a float, no need to adjust datetime.now(). If you did want to use datetime.now(), it has a `.timestamp` method which returns the same thing. – Andrew Nov 22 '18 at 06:00
  • You mean like this ? – aks Nov 22 '18 at 16:13
  • I think `int(time())` is exactly the answer to this question. I can't believe this has no upvotes after 18 months. – user1717828 Jun 12 '20 at 04:34
4

Short-hand to convert python date/datetime to Epoch (without microseconds)

int(current_date.strftime("%s")) # 2020-01-14  ---> 1578956400
int(current_datetime.strftime("%s")) # 2020-01-14 16:59:30.251176 -----> 1579017570
pymen
  • 5,737
  • 44
  • 35
3

Use strptime to parse the time, and call time() on it to get the Unix timestamp.

Sjoerd
  • 74,049
  • 16
  • 131
  • 175
1

enter image description hereI think this answer needs an update and the solution would go better this way.

from datetime import datetime

datetime.strptime("29.08.2011 11:05:02", "%d.%m.%Y %H:%M:%S").strftime("%s")

or you may use datetime object and format the time using %s to convert it into epoch time.

Akarsh Jain
  • 930
  • 10
  • 15