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 1263 aaronmk
def total_seconds(timedelta_): return timestamp(epoch + timedelta_)
26
27 1040 aaronmk
def now(): return datetime.datetime.now(utc)
28
29 817 aaronmk
def strftime(format, datetime_):
30
    '''datetime.strftime() can't handle years before 1900'''
31 1040 aaronmk
    return (datetime_.replace(year=epoch.year, day=1).strftime(format
32 845 aaronmk
        .replace('%Y', '%%Y')
33
        .replace('%d', '%%d')
34
        )
35
        .replace('%Y', '%04d' % datetime_.year)
36
        .replace('%d', '%02d' % datetime_.day)
37
        )
38 1040 aaronmk
39 1263 aaronmk
def strtotime(str_, default=epoch):
40
    import dateutil.parser
41
    return dateutil.parser.parse(str_, default=default)