如何基于时区偏移量将时间戳转换为指定时区的日期时间
Got it, let's break down how to convert your timestamp to the target timezone using that numeric offset (-7 hours). Here are two straightforward approaches you can use:
Approach 1: Manual Offset Adjustment with Timedelta
Since you already know how to get the UTC time, you can simply adjust it by the timezone offset using a timedelta object:
import datetime timestamp = 1571323748 utc_offset = -7 # Hours difference from UTC # Get the UTC datetime utc_dt = datetime.datetime.utcfromtimestamp(timestamp) # Calculate the offset as a timedelta offset = datetime.timedelta(hours=utc_offset) # Apply the offset to get the target timezone time target_dt = utc_dt + offset # Format and print the result print(target_dt.strftime("%Y-%m-%d %H:%M:%S")) # Output: 2019-10-17 07:49:08
This works because a timezone offset of -7 means the target time is 7 hours behind UTC. Adding the negative offset to UTC time effectively subtracts 7 hours, giving you the correct local time.
Approach 2: Use datetime.timezone for Proper Timezone Objects
For a more formal approach (and better compatibility with timezone-aware datetime operations), you can create a timezone object directly from the numeric offset:
import datetime timestamp = 1571323748 utc_offset = -7 # Hours difference from UTC # Create a timezone object using the offset target_tz = datetime.timezone(datetime.timedelta(hours=utc_offset)) # Option 1: Convert timestamp directly to target timezone target_dt = datetime.datetime.fromtimestamp(timestamp, tz=target_tz) # Option 2: Convert from a UTC-aware datetime (useful if you already have UTC time) utc_dt = datetime.datetime.utcfromtimestamp(timestamp).replace(tzinfo=datetime.timezone.utc) target_dt = utc_dt.astimezone(target_tz) # Format and print the result print(target_dt.strftime("%Y-%m-%d %H:%M:%S")) # Output: 2019-10-17 07:49:08
This method creates a proper timezone-aware datetime object, which is helpful if you need to perform further operations like comparisons or conversions with other timezones later.
Bonus: Handling Fractional Offsets
If your offset ever includes minutes (like -7.5 for UTC-7:30), this still works perfectly—timedelta(hours=-7.5) automatically converts the decimal into hours and minutes.
内容的提问来源于stack exchange,提问作者Kapil Choubisa

