The function below is designed to return a UTC offset string, in the form used widely by timestamps, of the user's current time for when only naive date time objects are available (no time zone information).
I've tested it on two systems, which are in different time zones, and it works perfectly. However I'd like confirmation that it will work on all systems running Python versions >= 2.6. Can anyone see any potential problems?
Note: The function will only ever be used with the user's current time and so present or past dates and times are not an issue.
import time
from datetime import datetime
def get_utc_offset_str():
"""
Returns a UTC offset string of the current time suitable for use in the
most widely used timestamps (i.e. ISO 8601, RFC 3339). For example:
10 hours ahead, 5 hours behind, and time is UTC: +10:00, -05:00, +00:00
"""
# Calculate the UTC time difference in seconds.
timestamp = time.time()
time_now = datetime.fromtimestamp(timestamp)
time_utc = datetime.utcfromtimestamp(timestamp)
utc_offset_secs = (time_now - time_utc).total_seconds()
# Flag variable to hold if the current time is behind UTC.
is_behind_utc = False
# If the current time is behind UTC convert the offset
# seconds to a positive value and set the flag variable.
if utc_offset_secs < 0:
is_behind_utc = True
utc_offset_secs *= -1
# Build a UTC offset string suitable for use in a timestamp.
if is_behind_utc:
pos_neg_prefix = "-"
else:
pos_neg_prefix = "+"
utc_offset = time.gmtime(utc_offset_secs)
utc_offset_fmt = time.strftime("%H:%M", utc_offset)
utc_offset_str = pos_neg_prefix + utc_offset_fmt
return utc_offset_str