Goodspeed

导航

统计

公告

2011年11月7日 #

Python中时间的处理之——tzinfo篇

#! /usr/bin/python
#
coding=utf-8

from datetime import datetime, tzinfo,timedelta

"""
tzinfo是关于时区信息的类
tzinfo是一个抽象类,所以不能直接被实例化
"""
class UTC(tzinfo):
"""UTC"""
def __init__(self,offset = 0):
self._offset = offset

def utcoffset(self, dt):
return timedelta(hours=self._offset)

def tzname(self, dt):
return "UTC +%s" % self._offset

def dst(self, dt):
return timedelta(hours=self._offset)

#北京时间
beijing = datetime(2011,11,11,0,0,0,tzinfo = UTC(8))
#曼谷时间
bangkok = datetime(2011,11,11,0,0,0,tzinfo = UTC(7))

#北京时间转成曼谷时间
beijing.astimezone(UTC(7))
#计算时间差时也会考虑时区的问题
timespan = beijing - bangkok

posted @ 2011-11-07 11:24 Goodspeed 阅读(115) 评论(0) 编辑

Python中时间的处理之——date和time篇

#! /usr/bin/python
#
coding=utf-8

from datetime import datetime,date,time

"""
date类型顾名思义就是只表示日期,而time只表示time
"""
today = date.today()

attrs = [
("year",""),( 'month',""),( 'day',"")
]
for k,v in attrs:
"today.%s = %s #%s" % (k,getattr(today, k),v)

#星期几。同datetime规则一样
today.isoweekday()
today.weekday()

#返回一个time结构,当然也就没有时间信息
today.timetuple()

#修改。同datetime规则一样
today.replace(month=1)

#转成字符串,不可以转回
today.strftime("%Y-%m-%d")

now = time(12,13,14)
attrs = [
("hour","小时"),( 'minute',""),( 'second',""),("microsecond","毫秒")
]
for k,v in attrs:
"now.%s = %s #%s" % (k,getattr(now, k),v)

#修改。同datetime规则一样
now.replace(minute=1)
#转成字符串,不可以转回
now.strftime("%H:%M:%S")

#date和time合并成datetime
print datetime.combine(today, now)



posted @ 2011-11-07 10:28 Goodspeed 阅读(75) 评论(0) 编辑