python timestamp转datetime_Python:如何将datetime / timestamp从一个时区转换为另一个时区?...

本文指导如何根据服务器系统时间和指定时区,处理时间转换,包括考虑夏令时等因素,使用pytz库实现轻松计算。推荐使用UTC作为系统标准,以避免比较时区问题。附带函数示例:convert_timestamp_to_timezone()

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)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值