Python:strftime UTC时间戳到本地时间格式 [英] Python: strftime a UTC timestamp to local time format

查看:629
本文介绍了Python:strftime UTC时间戳到本地时间格式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想使用数据库结果中的时间戳,并将其转换为我的语言环境时间格式。时间戳本身以UTC格式保存: 2015-03-30 07:19:06.746037 + 02 %d。%m。%Y%H:%M%z 打印value.strftime(格式) $ c>输出将是 30.03.2015 07:19 +0200 。这可能是用时区信息显示时间戳的正确方法,但不幸的是,这里的用户不习惯这样做。我想达到的是给定时间戳的以下内容: 30.03.2015 09:19 。现在,我通过

I'd like to use the timestamp from a database result and convert it to my locale time format. The timestamp itself is saved in UTC format: 2015-03-30 07:19:06.746037+02. After calling print value.strftime(format) with the format %d.%m.%Y %H:%M %z the output will be 30.03.2015 07:19 +0200. This might be the correct way to display timestamps with timezone information but unfortunately users here are not accustomed to that. What I want to achieve is the following for the given timestamp: 30.03.2015 09:19. Right now I'm adding two hours via

is_dst = time.daylight and time.localtime().tm_isdst > 0
utc_offset = - (tine.altzone if is_dst else time.timezone)
value = value + timedelta(seconds=utc_offset)

我想知道是否有更智能的解决方案来解决我的问题。 ( timestamp.tzinfo 有一个偏移量值,可以/应该使用它吗?解决方案需要DST知道)

I was wondering if there is a more intelligent solution to my problem. (timestamp.tzinfo has a offset value, can/should this be used instead? The solution needs to be DST aware too.)

推荐答案

这个SO贴子回答如何从timezoneed的时间戳获取当地时间。

基本上,使用tzlocal。

Basically, use tzlocal.

import time
from datetime import datetime

import pytz # $ pip install pytz
from tzlocal import get_localzone # $ pip install tzlocal

# get local timezone    
local_tz = get_localzone() 

# test it
# utc_now, now = datetime.utcnow(), datetime.now()
ts = time.time()
utc_now, now = datetime.utcfromtimestamp(ts), datetime.fromtimestamp(ts)

local_now = utc_now.replace(tzinfo=pytz.utc).astimezone(local_tz) # utc -> local
assert local_now.replace(tzinfo=None) == now

这篇关于Python:strftime UTC时间戳到本地时间格式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆