Skip to content

Instantly share code, notes, and snippets.

@akhsiM
Last active September 8, 2020 14:16
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
Star You must be signed in to star a gist
Save akhsiM/fcff55ff2794ee5ad644f1b9823b8ab4 to your computer and use it in GitHub Desktop.
from datetime import datetime, timedelta
from dateutil.tz import tzlocal
def convert_from_utc(input, offset=0, outputstr=True, tz=False):
'''
This operation accepts three arguments:
1. str input: Input with format specified below
2. int offset: Offset in hour(s). This may be needed for daylight saving. (optional)
3. bool ouputstr: If True (default), output is a string, else output is of type datetime.datetime
4. bool tz: If True, return Timezone-aware (only string) output
RULES:
Input has to be a string in the following format:
- yyyy-mm-ddTHH:MM:S.sssZ (There has to be at least one decimal point after second)
e.g: INPUT: 2020-05-20T12:25:21.123Z
Output will be in this format:
- String: yyyy-mm-dd HH:MM:SS {TZ}
e.g: 2020-05-20 22:25:21
or 2020-05-20 22:25:21 AEST (if tz=True)
- datetime.datetime format
Test:
>>> convert_from_utc('2002-01-04T03:15:43.000Z')
2002-01-04 13:15:43
>>> type(convert_from_utc('2002-01-04T03:15:43.000Z'))
<class 'str'>
>>> type(convert_from_utc('2002-01-04T03:15:43.000Z', outputstr=False))
<class 'datetime.datetime'>
'''
# Parse Inputs
if input == None:
return None
input = datetime.strptime(input, '%Y-%m-%dT%H:%M:%S.%fZ')
offset = timedelta(hours= offset)
# Calculate time difference between UTC and now,
# then round to nearest second
now = datetime.now(tzlocal())
utc_offset = now.tzinfo.utcoffset(now)
local_time = input + utc_offset + offset
if outputstr:
local_time_str = datetime.strftime(local_time, '%Y-%m-%d %H:%M:%S')
if tz:
local_time_str += f' {datetime.now(tzlocal()).tzname()}'
return local_time_str
else:
return local_time
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment