1

I've been struggling to determine how I can generate a POSIX (UNIX) time value for today and yesterday (midnight) via Python. I created this code, but keep stumbling with how to convert them to a POSIX value:

from datetime import datetime, timedelta
import time
today_string = datetime.now().strftime('%Y-%m-%d 00:00:00')
yesterday_string = (datetime.now() - timedelta(0)).strftime('%Y-%m-%d 00:00:00')

today = datetime.strptime(today_string, '%Y-%m-%d %H:%M:%S')
yesterday = datetime.strptime(yesterday_string, '%Y-%m-%d %H:%M:%S')

print time.mktime(today).timetuple()

This code yields an exception:

TypeError: argument must be 9-item sequence, not datetime.datetime

At this point, I'm at my wits end. Any help you can provide is appreciated.

Huuuze
  • 15,528
  • 25
  • 72
  • 91

3 Answers3

2

You should apply the timetuple() method to the today object, not to the result of time.mktime(today):

>>> time.mktime(today.timetuple())
1345845600.0

By the way, I'm wrong or yesterday will be equal to today in your code?

edit: To obtain the POSIX time for today you can simply do:

time.mktime(datetime.date.today().timetuple())
Bakuriu
  • 98,325
  • 22
  • 197
  • 231
1

@Bakuriu is right here. But you are making this overcomplex.

Take a look at this:

from datetime import date, timedelta
import time

today = date.today()
today_unix = time.mktime(today.timetuple())

yesterday = today - timedelta(1)
yesterday_unix = time.mktime(yesterday.timetuple())

Since the date object doesn't hold time, it resets it to the midnight.

You could also replace the last part with:

yesterday_unix = today_unix - 86400

but note that it wouldn't work correctly across daylight saving time switches (i.e. you'll end up with 1 AM or 23 PM).

Michał Górny
  • 18,713
  • 5
  • 53
  • 76
0

Getting a unix timestamp from a datetime object as a string and as a float:

datetime.now().strftime('%s')
'1345884732'

time.mktime(datetime.now().timetuple())
1345884732.0
gvalkov
  • 3,977
  • 30
  • 31