0

I'm trying to find the epoch seconds for the most recent midnight in Python.

I found this: What was midnight yesterday as an epoch time?

which has

from datetime import datetime, date, time
midnight = datetime.combine(date.today(), time.min)

'midnight' is now the right time...but how do I get it into epoch seconds? i.e., something like 1393997154 (or 1393997154.09)

Not saying the above the best approach. In perl, I would

my ($sec,$min,$hour,$mday,$mon,$year) = localtime(time);
$year += 1900;
return timelocal(0,0,0,$mday,$mon,$year);

...in other words, get the struct, change hour/min/sec, then convert it.

Community
  • 1
  • 1
raindog308
  • 772
  • 1
  • 10
  • 20
  • possible duplicate of [Convert python datetime to epoch with strftime](http://stackoverflow.com/questions/11743019/convert-python-datetime-to-epoch-with-strftime) – Andy Mar 05 '14 at 05:38

3 Answers3

4

You can use the strftime function with %s:

>>> import datetime
>>> datetime.date.today().strftime('%s')
'1393920000'
jterrace
  • 64,866
  • 22
  • 157
  • 202
3

To convert normal time format (yyyy-mm-dd hours:minutes:seconds) into epoch seconds, follow the code.

import datetime
import calendar
d = datetime.datetime(yyyy,mm,dd,hours,minutes,seconds)
calendar.timegm(d.timetuple())

EX: To calculate epoch time for 2014-03-04 12:00:00,

>>> import datetime
>>> import calendar
>>> d = datetime.datetime(2014,03,04,12,00,00)
>>> calendar.timegm(d.timetuple())
1393934400
Suresh Kota
  • 134
  • 1
  • 2
  • 8
0

If your epoch reference is time.time(), you can use :

now=list(time.localtime())
LocalMidnight=time.mktime(tuple(now[:3]+[0]*3+now[-3:]))
doom
  • 3,276
  • 4
  • 30
  • 41