Skip to content

Instantly share code, notes, and snippets.

@xyb
Last active March 19, 2020 10:52
Show Gist options
  • Save xyb/1cc1473c415789a275b92209a71a2996 to your computer and use it in GitHub Desktop.
Save xyb/1cc1473c415789a275b92209a71a2996 to your computer and use it in GitHub Desktop.
from datetime import datetime
def format_local_datetime(dt):
"""Return a string with local timezone representing the date."""
try:
return dt.astimezone().strftime('%Y-%m-%d %H:%M %z')
except (TypeError, ValueError):
# Python 2 do not have builtin timezone
import time
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)
now = datetime.now()
print(format_local_datetime(now))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment