xxxxxxxxxx
ts = now.strftime("%Y-%m-%d %H:%M:%S%z")
xxxxxxxxxx
#as an aware datetime
from datetime import datetime, timezone
utc_dt = datetime.now(timezone.utc) # UTC time
dt = utc_dt.astimezone() # local time
#or from pytz database
import pytz
tz = pytz.timezone('Europe/Berlin')
berlin_now = datetime.now(tz)
xxxxxxxxxx
import datetime
import pytz
my_date = datetime.datetime.now(pytz.timezone('US/Pacific'))
xxxxxxxxxx
import datetime
import pytz
d = datetime.datetime.now()
timezone = pytz.timezone("America/Los_Angeles")
# List of Time Zones: https://gist.github.com/heyalexej/8bf688fd67d7199be4a1682b3eec7568
d_aware = timezone.localize(d)
d_aware.tzinfo
# One Liner
timezone.localize(datetime.datetime.now())
# Timestamp to Datetime with timezone
datetime.fromtimestamp(3456789, timezone)
xxxxxxxxxx
from datetime import datetime, timedelta, timezone
from dateutil import tz
# Add or Replace timezone information
print(dt.replace(tzinfo=timezone.utc))
# create timezone of +5:30 UTC
IST = timezone(timedelta(hours=5, minutes=30))
# Timezone-aware datetime
dt = datetime(2017, 12, 30, 15, 9, 3, tzinfo = IST)
# Most useful function "tz.gettz()" when dealing with daylight saving situations
et = tz.gettz('America/New_York') # Another timezone
# Convert corresponding time to another timezone
print(dt.astimezone(et))
###### Ambiguous time #########
eastern = tz.gettz('US/Eastern')
first_1am = datetime(2017, 11, 5, 1, 0, 0, tzinfo = eastern)
# Check if there are multiple timespans (End of daylight saving time)
tz.datetime_ambiguous(first_1am)
second_1am = datetime(2017, 11, 5, 1, 0, 0, tzinfo = eastern)
# The folded timespan that recurs
second_1am = tz.enfold(second_1am)
# Duration in local time zone
(first_1am - second_1am).total_seconds()
# Duration in universal time
first_1am = first_1am.astimezone(tz.UTC)
second_1am = second_1am.astimezone(tz.UTC)
(second_1am - first_1am).total_seconds()
xxxxxxxxxx
from datetime import datetime
from pytz import timezone
format = "%Y-%m-%d %H:%M:%S %Z%z"
# Current time in UTC
now_utc = datetime.now(timezone('UTC'))
print(now_utc.strftime(format))
timezones = ['Asia/Dhaka', 'Europe/Berlin', 'America/Los_Angeles']
for tzone in timezones:
# Convert to Asia/Dhaka time zone
now_asia = now_utc.astimezone(timezone(tzone))
print(now_asia.strftime(format))
xxxxxxxxxx
# Importing necessary modules
from datetime import datetime, timezone, timedelta
# Create a timezone-aware datetime object
now = datetime.now(timezone.utc)
# Convert the timezone of the datetime object
desired_timezone = timezone(timedelta(hours=5)) # Example: converting to UTC+05:00 timezone
converted_time = now.astimezone(desired_timezone)
# Printing the converted time
print(converted_time)
xxxxxxxxxx
from time import gmtime, strftime
print(strftime("%z", gmtime()))