3

I'm trying to get todays and yesterdays time using Python's time module.

This for me works for todays date:

dt = time.strptime(time.strftime("%d/%m/%Y"),'%d/%m/%Y')

But I don't know how to get yesterdays date. I've found many tutorials where the datetime module is used but nothing where time module is used.

How can I do that? And is there a better way to get todays date (struct_time)?

Milano
  • 18,048
  • 37
  • 153
  • 353

3 Answers3

4

To get yesterday's struct_time, use any of many existing datetime solutions and call .timetuple() to get struct_time e.g.:

#!/usr/bin/env python
from datetime import date, timedelta

today = date.today()
yesterday = today - timedelta(1)
print(yesterday.timetuple())
# -> time.struct_time(tm_year=2015, tm_mon=4, tm_mday=22, tm_hour=0, tm_min=0, tm_sec=0, tm_wday=2, tm_yday=112, tm_isdst=-1)

It produces the correct day in the local timezone even around DST transitions.

See How can I subtract a day from a python date? if you want to find the corresponding UTC time (get yesterday as an aware datetime object).


You could also get yesterday using only time module (but less directly):

#!/usr/bin/env python
import time

def posix_time(utc_time_tuple):
    """seconds since Epoch as defined by POSIX."""
    # from https://gist.github.com/zed/ff4e35df3887c1f82002
    tm_year = utc_time_tuple.tm_year - 1900
    tm_yday = utc_time_tuple.tm_yday - 1
    tm_hour = utc_time_tuple.tm_hour
    tm_min = utc_time_tuple.tm_min
    tm_sec = utc_time_tuple.tm_sec
    # http://pubs.opengroup.org/stage7tc1/basedefs/V1_chap04.html#tag_04_15
    return (tm_sec + tm_min*60 + tm_hour*3600 + tm_yday*86400 +
            (tm_year-70)*31536000 + ((tm_year-69)//4)*86400 -
            ((tm_year-1)//100)*86400 + ((tm_year+299)//400)*86400)

now = time.localtime()
yesterday = time.gmtime(posix_time(now) - 86400)
print(yesterday)
# -> time.struct_time(tm_year=2015, tm_mon=4, tm_mday=22, tm_hour=22, tm_min=6, tm_sec=16, tm_wday=2, tm_yday=112, tm_isdst=0)

It assumes that time.gmtime() accepts POSIX timestamp on the given platform (Python's stdlib breaks otherwise e.g., if non-POSIX TZ=right/UTC is used). calendar.timegm() could be used instead of posix_time() but the former may use datetime internally.

Note: yesterday represents local time in both solutions (gmtime() is just a simple way to implement subtraction here). Both solutions use naive timezone-unaware time objects and therefore the result may be ambiguous or even non-existent time though unless the local timezone has skipped yesterday (e.g., Russia had skipped several days in February 1918) then the date is correct anyway.

Community
  • 1
  • 1
jfs
  • 399,953
  • 195
  • 994
  • 1,670
3

To start with, there is a more straight-forward way to get the current date:

dt = time.localtime()

To get the previous day's date, you need to subtract 24 hours from the current time. This might have some glitches around DST transitions but I'll leave those as an exercise for the reader.

dt = time.localtime(time.time() - 86400)
Mark Ransom
  • 299,747
  • 42
  • 398
  • 622
  • It does have some glitches around DST transition. Here's how to fix them: [Get yesterday's date in Python, DST-safe](http://stackoverflow.com/a/15345272/4279) -- the solution uses `datetime` module. To get the time tuple instead, call `.timetuple()` method on a `datetime` object. – jfs Apr 23 '15 at 19:34
  • @J.F.Sebastian I would have preferred a `datetime` solution too, but the OP specifically rejects that. – Mark Ransom Apr 23 '15 at 19:45
  • OP needs `struct_time`, here's a [simple `datetime`-based solution that returns `struct_time`](http://stackoverflow.com/a/29832960/4279). – jfs Apr 23 '15 at 19:49
1

If you have a time object given, you can convert it to a datetime first:

>>> import time
>>> import datetime

>>> dt = time.strptime(time.strftime("%d/%m/%Y"),'%d/%m/%Y')
>>> # base time object: time.struct_time(tm_year=2015, tm_mon=4, tm_mday=23, tm_hour=0, tm_min=0, tm_sec=0, tm_wday=3, tm_yday=113, tm_isdst=-1)

>>> a_datetime_obj = datetime.datetime.fromtimestamp(time.mktime(dt))
>>> # convert to datetime: 2015-04-23 00:00:00

>>> minus_one = a_datetime_obj - datetime.timedelta(days=1)
>>> # subtract one day: 2015-04-22 00:00:00

>>> print minus_one.timetuple()
>>> # get time object from datetime: time.struct_time(tm_year=2015, tm_mon=4, tm_mday=22, tm_hour=0, tm_min=0, tm_sec=0, tm_wday=2, tm_yday=112, tm_isdst=-1)
sthzg
  • 5,514
  • 2
  • 29
  • 50