python localtime 与utc时间差5分钟_从时区和UTC时间,获取在该时间点的秒与本地时间的差异...

这篇博客介绍了如何在Python中将UTC时间戳转换为特定时区(如'Europe/Stockholm')的本地时间,并计算与UTC的秒数差。通过使用`pytz`库,可以将POSIX时间戳转换为指定时区的datetime对象,然后获取与UTC的时间差。示例代码展示了两种不同的实现方法,确保了结果的准确性。
摘要由CSDN通过智能技术生成

This should be very simple, but I can't quite figure it out in Python.

I want to have a function which takes two arguments, a UTC time in seconds and a zoneinfo name like 'Europe/Vienna' and returns the offset in seconds from local time and UTC for that point in time.

In C it would be:

/* ... code to to set local time to the time zone I want to compare against,

not shown here. Then call function below to get difference vs localtime.

Hardly an ideal solution,

but just to demonstrate what I want in a "lingua franca" (C): */

int get_diff_vs_localtime(const time_t original_utc_time)

{

struct tm* ts;

ts = localtime(&original_utc_time);

return mktime(ts) - original_utc_time;

}

I guess my question really boils down to: "given an Olson timezone (example 'Europe/Stockholm') and a UTC time, what is the local time?

解决方案

Assuming "UTC time in seconds" means POSIX timestamp. To convert it to Stockholm time:

from datetime import datetime

import pytz

tz = pytz.timezone('Europe/Stockholm')

utc_dt = datetime.utcfromtimestamp(posix_timestamp).replace(tzinfo=pytz.utc)

dt = tz.normalize(utc_dt.astimezone(tz))

print(dt.strftime('%Y-%m-%d %H:%M:%S %Z%z'))

tz.normalize() is unnecessary if the source timezone is UTC (like in this case).

A simpler alternative is to use fromtimestamp()'s tz parameter, to convert "seconds since the epoch" to local time:

from datetime import datetime

import pytz

tz = pytz.timezone('Europe/Stockholm')

dt = datetime.fromtimestamp(posix_timestamp, tz)

print(dt.strftime('%Y-%m-%d %H:%M:%S %Z%z'))

Both examples produce the same result.

If local machine uses "right" timezones then to convert POSIX timestamp received from an external source to UTC, an explicit formula could be used:

from datetime import datetime, timedelta

import pytz

utc_dt = datetime(1970, 1, 1, tzinfo=pytz.utc) + timedelta(seconds=posix_timestamp)

The latest formula may also support a larger date range (less likely issues with dates before 1970, after 2038 or 3000 years).

If the timestamp comes from the local "right" source then the first two examples should be used instead (they call "right" time.gmtime()).

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值