How to get the current date/time string with different timezones like GMT-06:00
and GMT+02:00
?
from datetime import datetime, timedelta
def get_now_with_offset(offset_hours: int):
# turn offset hours to timedelta object
offset_td = timedelta(hours=offset_hours)
# utcnow is the GMT time with no offset hours
now = datetime.utcnow()
return (now + offset_td).strftime('%Y-%m-%d %H:%M:%S')
if __name__ == "__main__":
# GMT+02:00
print(get_now_with_offset(2))
# GMT-06:00
print(get_now_with_offset(-6))
Output example:
2022-06-17 14:00:59
2022-06-17 06:00:59
def get_offset_hours(time_zone: str = 'GMT+02:00') -> int:
offset_hours = int(time_zone.replace("GMT", "").split(":")[0])
assert -12 <= offset_hours <= 12
return offset_hours