Project

General

Profile

1
# Date/time manipulation
2

    
3
import datetime
4
import dateutil.tz
5
import time
6

    
7
utc = dateutil.tz.tzutc()
8
local = dateutil.tz.tzlocal()
9

    
10
def naive2utc(datetime_):
11
    assert datetime_.tzinfo == None
12
    return datetime_.replace(tzinfo=utc)
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_):
20
    datetime_ = aware2local(datetime_)
21
    return int(time.mktime(datetime_.timetuple())) + datetime_.microsecond/1e6
22

    
23
epoch = from_timestamp(0)
24

    
25
def total_seconds(timedelta_): return timestamp(epoch + timedelta_)
26

    
27
def now(): return datetime.datetime.now(utc)
28

    
29
def strftime(format, datetime_):
30
    '''datetime.strftime() can't handle years before 1900'''
31
    return (datetime_.replace(year=epoch.year, day=1).strftime(format
32
        .replace('%Y', '%%Y')
33
        .replace('%d', '%%d')
34
        )
35
        .replace('%Y', '%04d' % datetime_.year)
36
        .replace('%d', '%02d' % datetime_.day)
37
        )
38

    
39
def strtotime(str_, default=epoch):
40
    import dateutil.parser
41
    return dateutil.parser.parse(str_, default=default)
(3-3/17)