Specifically, given the timezone of my server (system time perspective) and a timezone input, how do I calculate the system time as if it were in that new timezone (regardless of daylight savings, etc)?
import datetime
current_time = datetime.datetime.now() #system time
server_timezone = "US/Eastern"
new_timezone = "US/Pacific"
current_time_in_new_timezone = ???
解决方案
If you know your server/system time and the new timezone you want to convert it to, use pytz.localize to handle any localization (e.g. daylight savings, etc), pytz.timezone to create timezone objects, and datetime.astimezone(timezone) for an easy calculation.
import datetime
import pytz # new import
current_time = datetime.datetime.now() #system time
server_timezone = pytz.timezone("US/Eastern")
new_timezone = pytz.timezone("US/Pacific")
# returns datetime in the new timezone. Profit!
current_time_in_new_timezone = server_timezone.localize(current_time).astimezone(new_timezone)
That said, for server-side processing involving time, consider using UTC as a system standard because comparisons between timezone-aware and timezone-non-aware timestamps simply don't work. To understand the problem more, see: http://lucumr.pocoo.org/2011/7/15/eppur-si-muove/
P.S. To make a timezone conversation function, try:
def convert_timestamp_to_timezone(timestamp, tz_old, tz_new):
return tz_old.localize(timestamp).astimezone(tz_new)
本文指导如何根据服务器系统时间和指定时区,处理时间转换,包括考虑夏令时等因素,使用pytz库实现轻松计算。推荐使用UTC作为系统标准,以避免比较时区问题。附带函数示例:convert_timestamp_to_timezone()
2433

被折叠的 条评论
为什么被折叠?



