Skip to content

Commit 4b18489

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

File tree

2 files changed

+28
-2
lines changed

2 files changed

+28
-2
lines changed

coverage/backward.py

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -9,6 +9,8 @@
99
import os
1010
import sys
1111

12+
from datetime import datetime
13+
1214
from coverage import env
1315

1416

@@ -217,6 +219,30 @@ def __eq__(self, other):
217219
return self.__dict__ == other.__dict__
218220

219221

222+
def format_local_datetime(dt):
223+
"""Return a string with local timezone representing the date."""
224+
try:
225+
return dt.astimezone().strftime('%Y-%m-%d %H:%M %z')
226+
except (TypeError, ValueError):
227+
# Class datetime.timezone introduced in Python 3.2
228+
# Datetime.astimezone in Python 3.5 can not handle naive datetime
229+
import time
230+
def get_timezone_offset():
231+
timestamp = time.time()
232+
delta = datetime.fromtimestamp(timestamp) - datetime.utcfromtimestamp(timestamp)
233+
if delta.seconds >= 0:
234+
sign = '+'
235+
seconds = delta.seconds
236+
else:
237+
sign = '-'
238+
seconds = - delta.seconds
239+
hours, rest = divmod(seconds, 60 * 60)
240+
minutes, _ = divmod(rest, 60)
241+
return '%s%02d%02d' % (sign, hours, minutes)
242+
offset = get_timezone_offset()
243+
return '%s %s' % (dt.strftime('%Y-%m-%d %H:%M'), offset)
244+
245+
220246
def invalidate_import_caches():
221247
"""Invalidate any import caches that may or may not exist."""
222248
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)