Last active
October 30, 2021 16:56
-
-
Save karpanGit/5dac53b1fe12db067c5e0d5df2eff2eb to your computer and use it in GitHub Desktop.
python, convert timezone
This file contains hidden or 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
| # 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