Revision 1040
Added by Aaron Marcuse-Kubitza almost 13 years ago
lib/dates.py | ||
---|---|---|
1 | 1 |
# Date/time manipulation |
2 | 2 |
|
3 | 3 |
import datetime |
4 |
import dateutil.tz |
|
4 | 5 |
import time |
5 | 6 |
|
6 |
epoch_year = datetime.datetime.utcfromtimestamp(0).year |
|
7 |
utc = dateutil.tz.tzutc() |
|
8 |
local = dateutil.tz.tzlocal() |
|
7 | 9 |
|
8 |
def timestamp(datetime_): return time.mktime(datetime_.timetuple()) |
|
10 |
def naive2utc(datetime_): |
|
11 |
assert datetime_.tzinfo == None |
|
12 |
return datetime_.replace(tzinfo=utc) |
|
9 | 13 |
|
14 |
def aware2local(datetime_): return datetime_.astimezone(local) |
|
15 |
|
|
16 |
def from_timestamp(utc_timestamp): |
|
17 |
return naive2utc(datetime.datetime.utcfromtimestamp(utc_timestamp)) |
|
18 |
|
|
19 |
def timestamp(datetime_): return time.mktime(aware2local(datetime_).timetuple()) |
|
20 |
|
|
21 |
epoch = from_timestamp(0) |
|
22 |
|
|
23 |
def now(): return datetime.datetime.now(utc) |
|
24 |
|
|
10 | 25 |
def strftime(format, datetime_): |
11 | 26 |
'''datetime.strftime() can't handle years before 1900''' |
12 |
return (datetime_.replace(year=epoch_year, day=1).strftime(format
|
|
27 |
return (datetime_.replace(year=epoch.year, day=1).strftime(format
|
|
13 | 28 |
.replace('%Y', '%%Y') |
14 | 29 |
.replace('%d', '%%d') |
15 | 30 |
) |
16 | 31 |
.replace('%Y', '%04d' % datetime_.year) |
17 | 32 |
.replace('%d', '%02d' % datetime_.day) |
18 | 33 |
) |
34 |
|
|
35 |
def total_seconds(timedelta_): return timestamp(epoch + timedelta_) |
Also available in: Unified diff
dates.py: Deal properly with different timezones by using external dateutil package. Added total_seconds() to replace datetime.timedelta.total_seconds() on Python before 2.7.