Skip to content

Commit 8306858

Browse files
committed
A helpber to format datetime with local timezone
1 parent f5e5b4a commit 8306858

File tree

2 files changed

+36
-2
lines changed

2 files changed

+36
-2
lines changed

coverage/backward.py

Lines changed: 34 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -217,6 +217,40 @@ def __eq__(self, other):
217217
return self.__dict__ == other.__dict__
218218

219219

220+
try:
221+
# Class datetime.timezone introduced in Python 3.2
222+
from datetime import timezone
223+
del timezone
224+
225+
from datetime import datetime
226+
227+
def format_local_datetime(dt):
228+
"""Return a string with local timezone representing the date."""
229+
return dt.astimezone().strftime('%Y-%m-%d %H:%M %z')
230+
except ImportError:
231+
# Python 2 do not have builtin timezone
232+
import time
233+
from datetime import datetime
234+
235+
def format_local_datetime(dt):
236+
"""Return a string with local timezone representing the date."""
237+
def get_timezone_offset():
238+
timestamp = time.time()
239+
delta = datetime.fromtimestamp(timestamp) - datetime.utcfromtimestamp(timestamp)
240+
if delta.seconds >= 0:
241+
sign = '+'
242+
seconds = delta.seconds
243+
else:
244+
sign = '-'
245+
seconds = - delta.seconds
246+
hours, rest = divmod(seconds, 60 * 60)
247+
minutes, _ = divmod(rest, 60)
248+
return '%s%02d%02d' % (sign, hours, minutes)
249+
250+
offset = get_timezone_offset()
251+
return '%s %s' % (dt.strftime('%Y-%m-%d %H:%M'), offset)
252+
253+
220254
def invalidate_import_caches():
221255
"""Invalidate any import caches that may or may not exist."""
222256
if importlib and hasattr(importlib, "invalidate_caches"):

coverage/html.py

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -11,7 +11,7 @@
1111

1212
import coverage
1313
from coverage import env
14-
from coverage.backward import iitems, SimpleNamespace
14+
from coverage.backward import iitems, SimpleNamespace, format_local_datetime
1515
from coverage.data import add_data_to_hash
1616
from coverage.files import flat_rootname
1717
from coverage.misc import CoverageException, ensure_dir, file_be_gone, Hasher, isolate_module
@@ -200,7 +200,7 @@ def __init__(self, cov):
200200
'__url__': coverage.__url__,
201201
'__version__': coverage.__version__,
202202
'title': title,
203-
'time_stamp': datetime.datetime.now().astimezone().strftime('%Y-%m-%d %H:%M %z'),
203+
'time_stamp': format_local_datetime(datetime.datetime.now()),
204204
'extra_css': self.extra_css,
205205
'has_arcs': self.has_arcs,
206206
'show_contexts': self.config.show_contexts,

0 commit comments

Comments
 (0)