Skip to content

Instantly share code, notes, and snippets.

@karpanGit
Last active October 30, 2021 16:56
Show Gist options
  • Select an option

  • Save karpanGit/5dac53b1fe12db067c5e0d5df2eff2eb to your computer and use it in GitHub Desktop.

Select an option

Save karpanGit/5dac53b1fe12db067c5e0d5df2eff2eb to your computer and use it in GitHub Desktop.
python, convert timezone
# convert timezone (vanilla python)
from datetime import datetime, timezone, timedelta
# get the current local time, including the timezone
now = datetime.now().astimezone()
print(now)
# this simply changes the timezone to UTC
print(now.replace(tzinfo=timezone.utc))
# this converts the time correctly to UTC
print(datetime.fromtimestamp(now.timestamp(), tz=timezone.utc))
# convert timezone (using dateutil)
from datetime import datetime
from dateutil import tz
now = datetime.now(tz=tz.tzlocal())
print(now)
now_utc = now.astimezone(tz=tz.tzutc())
print(now_utc)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment