modifying a time.struct_time
Jason Friedman
jason at powerpull.net
Sat Dec 24 01:04:19 EST 2011
On Fri, Dec 16, 2011 at 10:44 AM, Chris Angelico <rosuav at gmail.com> wrote:
> On Fri, Dec 16, 2011 at 8:45 PM, Ulrich Eckhardt
> <ulrich.eckhardt at dominolaser.com> wrote:
>> I'm trying to create a struct_time that is e.g. one year ahead or a month
>> back in order to test some parsing/formatting code with different dates.
>
> Do you need it to be one exact calendar year, or would it make sense
> to add/subtract integers from a Unix time?
>
> t = time.time() + 365*86400 # Not actually a year ahead, it's 365 days ahead
> t = time.localtime(t) # if you want a struct_time
>
> ChrisA
> --
Not particularly elegant, but I believe accurate and relying only on
the stated struct_time contract:
#!/usr/bin/env python
# 2.7.2
import time, itertools
def is_local_time_different_by_one_year(time1, time2):
if abs(time1.tm_year - time2.tm_year) != 1:
return False
if abs(time1.tm_mon - time2.tm_mon ) != 0:
return False
if abs(time1.tm_mday - time2.tm_mday) != 0:
return False
if abs(time1.tm_hour - time2.tm_hour) != 0:
return False
if abs(time1.tm_min - time2.tm_min ) != 0:
return False
if abs(time1.tm_sec - time2.tm_sec ) != 0:
return False
return True
t = time.time()
time1 = time.localtime(t)
print("Local time is {}.".format(time1))
for i in itertools.count(0):
t += 1 # Add one second until we have reached next year
time2 = time.localtime(t)
if is_local_time_different_by_one_year(time1, time2):
print("One year later is {}".format(time2))
break
Not exactly a speed demon, either:
$ time python timediff.py
Local time is time.struct_time(tm_year=2011, tm_mon=12, tm_mday=24,
tm_hour=5, tm_min=57, tm_sec=44, tm_wday=5, tm_yday=358, tm_isdst=0).
One year later is time.struct_time(tm_year=2012, tm_mon=12,
tm_mday=24, tm_hour=5, tm_min=57, tm_sec=44, tm_wday=0, tm_yday=359,
tm_isdst=0)
real 3m8.922s
user 2m2.470s
sys 1m1.760s
More information about the Python-list
mailing list