Skip to content

Commit

Permalink
A helpber to format datetime with local timezone
Browse files Browse the repository at this point in the history
  • Loading branch information
xyb committed Mar 19, 2020
1 parent f5e5b4a commit 8306858
Show file tree
Hide file tree
Showing 2 changed files with 36 additions and 2 deletions.
34 changes: 34 additions & 0 deletions coverage/backward.py
Expand Up @@ -217,6 +217,40 @@ def __eq__(self, other):
return self.__dict__ == other.__dict__


try:
# Class datetime.timezone introduced in Python 3.2
from datetime import timezone
del timezone

from datetime import datetime

def format_local_datetime(dt):
"""Return a string with local timezone representing the date."""
return dt.astimezone().strftime('%Y-%m-%d %H:%M %z')
except ImportError:
# Python 2 do not have builtin timezone
import time
from datetime import datetime

def format_local_datetime(dt):
"""Return a string with local timezone representing the date."""
def get_timezone_offset():
timestamp = time.time()
delta = datetime.fromtimestamp(timestamp) - datetime.utcfromtimestamp(timestamp)
if delta.seconds >= 0:
sign = '+'
seconds = delta.seconds
else:
sign = '-'
seconds = - delta.seconds
hours, rest = divmod(seconds, 60 * 60)
minutes, _ = divmod(rest, 60)
return '%s%02d%02d' % (sign, hours, minutes)

offset = get_timezone_offset()
return '%s %s' % (dt.strftime('%Y-%m-%d %H:%M'), offset)


def invalidate_import_caches():
"""Invalidate any import caches that may or may not exist."""
if importlib and hasattr(importlib, "invalidate_caches"):
Expand Down
4 changes: 2 additions & 2 deletions coverage/html.py
Expand Up @@ -11,7 +11,7 @@

import coverage
from coverage import env
from coverage.backward import iitems, SimpleNamespace
from coverage.backward import iitems, SimpleNamespace, format_local_datetime
from coverage.data import add_data_to_hash
from coverage.files import flat_rootname
from coverage.misc import CoverageException, ensure_dir, file_be_gone, Hasher, isolate_module
Expand Down Expand Up @@ -200,7 +200,7 @@ def __init__(self, cov):
'__url__': coverage.__url__,
'__version__': coverage.__version__,
'title': title,
'time_stamp': datetime.datetime.now().astimezone().strftime('%Y-%m-%d %H:%M %z'),
'time_stamp': format_local_datetime(datetime.datetime.now()),
'extra_css': self.extra_css,
'has_arcs': self.has_arcs,
'show_contexts': self.config.show_contexts,
Expand Down

0 comments on commit 8306858

Please sign in to comment.