如何`strftime`调整时区? [英] How to `strftime` having timezone adjusted?

查看:288
本文介绍了如何`strftime`调整时区?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我这样存储我的datetime int UTC:

I store my datetime int UTC like so:

import pytz, datetime

timeUTC = datetime.datetime(2013, 5, 23, 19, 27, 50, 0)
timezoneLocal = pytz.timezone('Europe/Vilnius')

timeLocal = timezoneLocal.localize(timeUTC)

但是当我尝试打印时,它只是给我提供常规的UTC时间

But when I try to print it, it just gives me regular UTC hours

>>> timeLocal.strftime('%H:%M:%S')
'19:27:50'

我希望这会返回 '22:27:50',因为这是当地时间( pytz.timezone('Europe / Vilnius')现在是+3)。我在这里缺少什么?

I would expect this to return '22:27:50' since this is the local time (pytz.timezone('Europe/Vilnius') is +3 at the moment). What am I missing here?

推荐答案

将日期字符串本地化为UTC日期时间,然后使用 astimezone 转换为本地时区。

Localize the date string as a UTC datetime, then use astimezone to convert it to the local timezone.

import pytz, datetime

timeUTC = datetime.datetime(2013, 5, 23, 19, 27, 50, 0)
timezoneLocal = pytz.timezone('Europe/Vilnius')
utc = pytz.utc
timeLocal = utc.localize(timeUTC).astimezone(timezoneLocal)
print(timeLocal)
# 2013-05-23 22:27:50+03:00

本地化不会转换日期时间,它将日期字符串解释为尽管它是在那个时区写的。 localize 可以在朴素的日期时间(例如 timeUTC )中构建时区感知日期时间。 astimezone 将可识别时区的日期时间转换为其他时区。

localize does not convert datetimes, it interprets the date string as though it were written in that timezone. localize builds a timezone-aware datetime out of a naive datetime (such as timeUTC). astimezone converts timezone-aware datetimes to other timezones.

这篇关于如何`strftime`调整时区?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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