在Python中使用时区获取当前时间? [英] Getting current time with timezone in python?

查看:596
本文介绍了在Python中使用时区获取当前时间?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用Google App Engine和python。我不能安装第三方库。



虽然这应该可以工作,但它实际运行时没有错误,但它返回当前时间时区未应用。



我做错了什么?

  from datetime import tzinfo, timedelta,datetime 
$ b $ class类别:Seoul_tzinfo(tzinfo):
def utcoffset(self,dt):
return timedelta(hours = 9)
def dst(self,dt ):
return timedelta(0)
$ b $ greeting.date = datetime.now(Seoul_tzinfo())


解决方案

您是否在谈论从数据库中提取实体的时间?如果是这样,appengine以UTC存储所有dt属性;当你把(),它只是丢弃tz信息。最明智的做法是将你的dt转换为UTC(使用astimezone()),并在你从数据存储中获取时转换回来。

http://code.google.com/appengine/docs/python/datastore/typesandpropertyclasses.html#DateTimeProperty =nofollow> http://code.google.com/appengine/docs/python/datastore/typesandpropertyclasses .html#DateTimeProperty )


I'm using Google App Engine with python. And I can't install third party library.

I though this should work, but it actually runs without error but it returns current time timezone is not applied.

What did I do wrong?

from datetime import tzinfo, timedelta, datetime

class Seoul_tzinfo(tzinfo):
    def utcoffset(self, dt):
        return timedelta(hours=9)
    def dst(self, dt):
        return timedelta(0)

greeting.date = datetime.now( Seoul_tzinfo() )

解决方案

Are you talking about when the entity is fetched from the database? If so, appengine stores all dt properties in UTC; when you put(), it simply discards the tz info. The wisest thing would be to convert your dt to UTC (using astimezone()), and convert back when you fetch it from the datastore.

(See http://code.google.com/appengine/docs/python/datastore/typesandpropertyclasses.html#DateTimeProperty )

这篇关于在Python中使用时区获取当前时间?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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