-
Notifications
You must be signed in to change notification settings - Fork 2
/
timekit.py
191 lines (149 loc) · 4.81 KB
/
timekit.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
#!/usr/bin/python
# -*- coding: utf-8 -*-
"""
Copyright (c) 2012, Rui Carmo
Description: Utility functions for handling date and time information
License: MIT (see LICENSE.md for details)
"""
import time
import math
import re
import logging
import datetime
import gettext
gettext.textdomain('date')
_ = gettext.gettext
log = logging.getLogger()
# Embrace and extend Mark's feedparser mechanism
_textmate_date_re = \
re.compile('(\d{4})-(\d{2})-(\d{2})\s+(\d{2}):(\d{2}):(\d{2})$')
def parse_date(date):
"""Parse a TextMate date (YYYY-MM-DD HH:MM:SS, no time zone, assume it's always localtime)"""
m = _textmate_date_re.match(date)
try:
from feedparser import _parse_date
if not m:
return time.mktime(_parse_date(date))
except:
pass
return time.mktime(time.localtime(calendar.timegm(time.gmtime(time.mktime(time.strptime(date,
'%Y-%m-%d %H:%M:%S'))))))
def iso_time(value=None):
"""Format a timestamp in ISO format"""
if value == None:
value = time.localtime()
tz = time.timezone / 3600
return time.strftime('%Y-%m-%dT%H:%M:%S-', value) + '%(tz)02d:00' \
% vars()
def http_time(value=None):
"""Format a timestamp for HTTP headers"""
if value == None:
value = time.time()
return time.strftime('%a, %d %b %Y %H:%M:%S GMT',
time.gmtime(value))
def plain_date(date, rss=False):
"""Format a date consistently"""
if isinstance(date, float) or isinstance(date, int):
date = time.localtime(date)
# trickery to replace leading zero in month day
mday = time.strftime(' %d', date).replace(' 0', ' ').strip()
weekday = _(time.strftime('%A', date))
month = _(time.strftime('%b', date))
year = time.strftime('%Y', date)
# build English ordinal suffixes
day = int(mday)
if day > 20:
day = int(mday[1])
try:
suffix = ['th', 'st', 'nd', 'rd'][day]
except:
suffix = 'th'
if rss:
return _('rss_update_date_format') % locals()
else:
return _('journal_date_format') % locals()
def fuzzy_time(date=None):
intervals = {
'00:00-00:59': 'latenight',
'01:00-03:59': 'weehours',
'04:00-06:59': 'dawn',
'07:00-08:59': 'breakfast',
'09:00-12:29': 'morning',
'12:30-14:29': 'lunchtime',
'14:30-16:59': 'afternoon',
'17:00-17:29': 'teatime',
'17:30-18:59': 'lateafternoon',
'19:00-20:29': 'evening',
'20:30-21:29': 'dinnertime',
'21:30-22:29': 'night',
'22:30-23:59': 'latenight',
}
if isinstance(date, float) or isinstance(date, int):
date = time.localtime(date)
then = time.strftime('%H:%M', date)
for i in intervals.keys():
(l, u) = i.split('-')
# cheesy (but perfectly usable) string comparison
if l <= then and then <= u:
return _(intervals[i])
return None
def relative_time(value=None, addtime=False):
"""
A simple time string
"""
value = float(value)
if addtime:
format = ', %H:%M'
else:
format = ''
if time.localtime(value)[0] != time.localtime()[0]:
# we have a different year
format = ' %Y' + format
format = time.strftime('%b', time.localtime(value)) + ' %d' \
+ format
return time.strftime(format, time.localtime(value)).strip()
def time_since(older=None, newer=None, detail=2):
"""
Human-readable time strings, based on Natalie Downe's code from
http://blog.natbat.co.uk/archive/2003/Jun/14/time_since
Assumes time parameters are in seconds
"""
intervals = { # corrected from the initial 31536000
31556926: 'year',
2592000: 'month',
604800: 'week',
86400: 'day',
3600: 'hour',
60: 'minute',
}
chunks = intervals.keys()
# Reverse sort using a lambda for Python 2.3 compatibility
chunks.sort(lambda x, y: y - x)
if newer == None:
newer = time.time()
interval = newer - older
if interval < 0:
return _('some_time')
# We should ideally do this:
# raise ValueError('Time interval cannot be negative')
# but it makes sense to fail gracefully here
if interval < 60:
return _('less_1min')
output = ''
for steps in range(detail):
for seconds in chunks:
count = math.floor(interval / seconds)
unit = intervals[seconds]
if count != 0:
break
if count > 1:
unit = unit + 's'
if count != 0:
output = output + '%d %s, ' % (count, _(unit))
interval = interval - count * seconds
output = output[:-2]
return output
def datetime_to_epoch(dt):
epoch = datetime.datetime.utcfromtimestamp(0)
delta = dt - epoch
return delta.total_seconds()