Project

General

Profile

1 817 aaronmk
# Date/time manipulation
2
3
import datetime
4 1040 aaronmk
import dateutil.tz
5 817 aaronmk
import time
6
7 1040 aaronmk
utc = dateutil.tz.tzutc()
8
local = dateutil.tz.tzlocal()
9 817 aaronmk
10 1040 aaronmk
def naive2utc(datetime_):
11
    assert datetime_.tzinfo == None
12
    return datetime_.replace(tzinfo=utc)
13 817 aaronmk
14 1040 aaronmk
def aware2local(datetime_): return datetime_.astimezone(local)
15
16
def from_timestamp(utc_timestamp):
17
    return naive2utc(datetime.datetime.utcfromtimestamp(utc_timestamp))
18
19 1041 aaronmk
def timestamp(datetime_):
20
    datetime_ = aware2local(datetime_)
21
    return int(time.mktime(datetime_.timetuple())) + datetime_.microsecond/1e6
22 1040 aaronmk
23
epoch = from_timestamp(0)
24
25
def now(): return datetime.datetime.now(utc)
26
27 817 aaronmk
def strftime(format, datetime_):
28
    '''datetime.strftime() can't handle years before 1900'''
29 1040 aaronmk
    return (datetime_.replace(year=epoch.year, day=1).strftime(format
30 845 aaronmk
        .replace('%Y', '%%Y')
31
        .replace('%d', '%%d')
32
        )
33
        .replace('%Y', '%04d' % datetime_.year)
34
        .replace('%d', '%02d' % datetime_.day)
35
        )
36 1040 aaronmk
37
def total_seconds(timedelta_): return timestamp(epoch + timedelta_)