Created
November 21, 2019 15:00
-
-
Save lazyfrosch/dca0e10e1d1955204604454350c04169 to your computer and use it in GitHub Desktop.
Time parsing and conversion in Python
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from datetime import datetime | |
from pytz import timezone | |
from dateutil.parser import parse | |
def get_unix_time(time_string, tz_name): | |
# parse the time input (without timezone) | |
ts = parse(time_string) | |
# localize to the specified timezone | |
tz = timezone(tz_name) | |
ts = tz.localize(ts) | |
return int(ts.timestamp()) | |
ts = get_unix_time('21.11.2019 15:30', 'Europe/Berlin') | |
print(ts) | |
local = datetime.utcfromtimestamp(int(ts)) | |
local = timezone('UTC').localize(local) | |
local = local.astimezone(timezone('Europe/Berlin')) | |
print(local) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment