Files
Esmart/test.py
lychang 37af6c33ee init
2025-09-16 01:54:46 +08:00

31 lines
1021 B
Python
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

import datetime
import pytz
# 时间字符串转UTC时间的函数
def convert_to_utc(time_str, time_format='%Y-%m-%d %H:%M:%S', source_timezone=None):
# 解析时间字符串为datetime对象
local_dt = datetime.datetime.strptime(time_str, time_format)
# 如果指定了源时区则将本地时间转换为UTC时间
if source_timezone:
tz = pytz.timezone(source_timezone)
local_dt = tz.localize(local_dt)
utc_dt = local_dt.astimezone(pytz.UTC)
else:
# 如果没有指定源时区则假设时间字符串已经是UTC时间
utc_dt = pytz.UTC.localize(local_dt)
return utc_dt
# 示例用法
time_str = '2024-05-20 14:30:00'
# 假设时间字符串是北京时间(UTC+8)
utc_time = convert_to_utc(time_str, source_timezone='Asia/Shanghai')
print(convert_to_utc(time_str).timestamp())
print(f'UTC时间: {utc_time.strftime("%Y-%m-%d %H:%M:%S")}')
# 如果需要获取UTC时间戳
timestamp = utc_time.timestamp()
print(f'UTC时间戳: {timestamp}')