如何通过UTC偏移值获取指定时区当前时间?
How to Implement
get_current_time with UTC Offset Here's a clean, straightforward implementation using Python's built-in datetime module—no external libraries needed!
import datetime def get_current_time(utc_value): # Split the offset string into hours and minutes components hours_part, minutes_part = utc_value.split(':') # Convert parts to integers (handles positive/negative signs automatically) hours = int(hours_part) minutes = int(minutes_part) # Create a timedelta representing the UTC offset offset_delta = datetime.timedelta(hours=hours, minutes=minutes) # Make a timezone object from the delta target_timezone = datetime.timezone(offset_delta) # Fetch the current time in the target timezone current_time = datetime.datetime.now(target_timezone) # Optional: Return a formatted string instead of a datetime object (uncomment below) # return current_time.strftime("%Y-%m-%d %H:%M:%S %Z") return current_time # Test the function print(get_current_time("+05:30"))
Breakdown of How It Works:
- Parsing the Offset: The input string (like "+05:30") gets split into hours and minutes. Using
int()directly on the hours part handles both positive and negative offsets without extra sign-checking. - Timezone Object: We create a
datetime.timezoneusing atimedelta—this ensures we're working with a timezone-aware object, not just raw time values. - Current Time:
datetime.datetime.now(target_timezone)pulls the current local time for the specified offset, automatically adjusting from UTC.
Quick Notes:
- If you want a human-readable string instead of a
datetimeobject, uncomment thestrftimeline. The%Zplaceholder will show the offset (e.g.,+0530for Indian Standard Time). - This works for fixed UTC offsets (like "+05:30" or "-08:00"). It doesn’t handle timezones with daylight saving time changes—for that, you’d need a timezone database (like Python 3.9+'s
zoneinfo), but that’s outside the scope of the original requirement.
内容的提问来源于stack exchange,提问作者Shubham srivastava
相关产品推荐
相关产品推荐

