我想在Python中将当前时间转换为+0900.
这样做的恰当方法是什么(假设在时间模块中)?
我已经读过这不包含在Python中,你必须使用像pytz这样的东西.
我不希望在服务器或全局上更改它,只是在这一个实例中.
Alv*_*oAV 11
from datetime import datetime
from pytz import timezone
format = "%Y-%m-%d %H:%M:%S %Z%z"
# Current time in UTC
now_utc = datetime.now(timezone('UTC'))
print now_utc.strftime(format)
Output: 2015-05-18 10:02:47 UTC+0000
# Convert to Asia/Kolkata time zone
now_asia = now_utc.astimezone(timezone('Asia/Kolkata'))
print now_asia.strftime(format)
Output: 2015-05-18 15:32:47 IST+0530
Run Code Online (Sandbox Code Playgroud)
jfs*_*jfs 10
我想在Python中将当前时间转换为+0900 ...
我不想在服务器或全局上更改它,只是在这一个实例中.
要获取+0900
UTC时区偏移的当前时间:
from datetime import datetime, timedelta
current_time_in_utc = datetime.utcnow()
result = current_time_in_utc + timedelta(hours=9)
Run Code Online (Sandbox Code Playgroud)
除非您还使用pytz库,否则不要使用感知日期时间对象,否则由于DST转换和其他时区更改,您可能会得到错误的结果.如果你需要在datetime对象上做一些算术; 首先将它们转换为UTC.
您可以改用datetime
模块.改编自http://docs.python.org/library/datetime.html#datetime.tzinfo.fromutc
from datetime import tzinfo, timedelta, datetime
class FixedOffset(tzinfo):
def __init__(self, offset):
self.__offset = timedelta(hours=offset)
self.__dst = timedelta(hours=offset-1)
self.__name = ''
def utcoffset(self, dt):
return self.__offset
def tzname(self, dt):
return self.__name
def dst(self, dt):
return self.__dst
print datetime.now()
print datetime.now(FixedOffset(9))
Run Code Online (Sandbox Code Playgroud)
得到:
2011-03-12 00:28:32.214000
2011-03-12 14:28:32.215000+09:00
Run Code Online (Sandbox Code Playgroud)
当我运行它(我是UTC-0500另一天,然后DST开始)