Python:如何将datetime / timestamp从一个时区转换为另一个时区? [英] Python: How do you convert datetime/timestamp from one timezone to another timezone?

查看:691
本文介绍了Python:如何将datetime / timestamp从一个时区转换为另一个时区?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

具体来说,考虑到我的服务器的时区(系统时间视角)和时区输入,我如何计算系统时间,就像在这个新的时区(不管夏令时,等等)吗?

  import datetime 
current_time = datetime.datetime.now()#system time

server_timezone =US /东部
new_timezone =US / Pacific

current_time_in_new_timezone = ???


解决方案

如果你知道你的服务器/系统时间和新的您要将其转换为时区,使用 pytz.localize 来处理任何本地化(例如夏令时等), pytz.timezone 来创建时区对象,而 datetime.astimezone(timezone)可以轻松计算。

  import datetime 
import pytz#new import

current_time = datetime.datetime.now()#system time

server_timezone = pytz。 timezone(US / Eastern)$​​ b $ b new_timezone = pytz.timezone(US / Pacific)

#返回新时区的datetime。利润!
current_time_in_new_timezone = server_timezone.localize(current_time).astimezone(new_timezone)

涉及时间的服务器端处理考虑使用UTC作为系统标准,因为时区感知和时区无感知时间戳之间的比较根本不起作用。要了解更多的问题,请参阅: http://lucumr.pocoo。 org / 2011/7/15 / eppur-si-muove /



PS要进行时区会话功能,请尝试:

  def convert_timestamp_to_timezone(timestamp,tz_old,tz_new):
return tz_old。本地化(时间戳).astimezone(tz_new)


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)

这篇关于Python:如何将datetime / timestamp从一个时区转换为另一个时区?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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