Python: strftime a UTC timestamp to local time format

 ̄綄美尐妖づ 提交于 2019-12-25 01:47:16

问题


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)

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.)


回答1:


In your question the timestamp is already in desired timezone, so you don't need to do anything.

If you want to convert it to some other timezone you should be able to use;

YourModel.datetime_column.op('AT TIME ZONE')('your timezone name')

or,

func.timezone('your timezone name', YourModel.datetime_column)

in SQLAlchemy level.

On python level, consider using pytz




回答2:


You don't need to do conversions manually when you use time zone aware database timestamps unless the timezone you want to display is different from the system timezone. When you read and write datetime objects to the database the timezone info of the datetime object is taken into account, this means what you get back is the time in the local time zone, in your case +0200.




回答3:


This SO post answers how to get local time from a timezoned timestamp.

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


来源:https://stackoverflow.com/questions/29344289/python-strftime-a-utc-timestamp-to-local-time-format

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!