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 now(): return datetime.datetime.now(utc)
26

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

    
37
def total_seconds(timedelta_): return timestamp(epoch + timedelta_)
(3-3/16)