31 lines
1021 B
Python
31 lines
1021 B
Python
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}') |