You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何通过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.timezone using a timedelta—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 datetime object, uncomment the strftime line. The %Z placeholder will show the offset (e.g., +0530 for 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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.21 07:00:06