python如何显示时间_如何获取Python显示当前时间(东部时间)

How can I get Python to display the time in eastern?

I've looked over the python documentation but it's pretty confusing. I'm using Python 3.

Thanks.

解决方案

You should use the package pytz if you'll be needing a lot of time zones, and you need to correctly handle the duplicate hour of daylight savings time (i.e. what happens from midnight to 1am).

For something simple though, it's easy enough to create your own time zone class:

import datetime

class EST5EDT(datetime.tzinfo):

def utcoffset(self, dt):

return datetime.timedelta(hours=-5) + self.dst(dt)

def dst(self, dt):

d = datetime.datetime(dt.year, 3, 8) #2nd Sunday in March

self.dston = d + datetime.timedelta(days=6-d.weekday())

d = datetime.datetime(dt.year, 11, 1) #1st Sunday in Nov

self.dstoff = d + datetime.timedelta(days=6-d.weekday())

if self.dston <= dt.replace(tzinfo=None) < self.dstoff:

return datetime.timedelta(hours=1)

else:

return datetime.timedelta(0)

def tzname(self, dt):

return 'EST5EDT'

dt = datetime.datetime.now(tz=EST5EDT())

Here you are using the abstract base class datetime.tzinfo to create a EST5EDT class which describes what it means to be "Eastern Time Zone", namely your UTC offset (-5 hours) and when daylight savings time is in effect (btwn the 2nd Sunday of March and the 1st Sunday of November).

Btw the template above is pulled from the datetime docs:

http://docs.python.org/library/datetime.html

Not sure what you mean "get Python to display the time in eastern", but using the dt object from the last line above:

In [15]: print(dt)

2012-07-29 12:28:59.125975-04:00

In [16]: print(dt.strftime('%Y-%m-%d %H:%M:%S'))

2012-07-29 12:28:59

In [17]: print(dt.strftime('%H:%M:%S'))

12:28:59

In [18]: print(dt.strftime('%s.%f'))

1343579339.125975

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值