Milano
Milano

Reputation: 18705

Time - get yesterdays date

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)?

Upvotes: 4

Views: 8498

Answers (3)

jfs
jfs

Reputation: 414139

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.

Upvotes: 4

sthzg
sthzg

Reputation: 5554

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)

Upvotes: 1

Mark Ransom
Mark Ransom

Reputation: 308111

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)

Upvotes: 3

Related Questions