GeezerVisonThe World Wide Web, restored to 800 pixels of glory. |
| Home|About|Gaming cabinet|Archives|How it works|Starter sites |
GeezerVison is showing tracholar.github.io — Python 日期时间相关模块总结 - Tracholar的个人wiki Python 日期时间相关模块总结
Table of Contents
简介Python标准库提供了对日期、时间、日历进行操作的模块 time 模块
这个模块提供的时间操作函数主要是时间戳,时间字符串和 基本用法生成Unix时间戳,单位是秒 >>> ts = time.time() >>> ts 1445495655.495 时间戳是一个浮点数,可以通过内置函数转换为其他格式。 时间戳转换为 >>> time.gmtime(ts) time.struct_time(tm_year=2015, tm_mon=10, tm_mday=22, tm_hour=6, tm_min=34, tm_sec=15, tm_wday=3, tm_yday=295, tm_isdst=0) >>> time.localtime(ts) time.struct_time(tm_year=2015, tm_mon=10, tm_mday=22, tm_hour=14, tm_min=34, tm_sec=15, tm_wday=3, tm_yday=295, tm_isdst=0) 时间戳转换为方便阅读的字符串 >>> time.ctime(ts) 'Thu Oct 22 14:34:15 2015'
>>> st = time.localtime(ts) >>> time.asctime(st) 'Thu Oct 22 14:34:15 2015' >>> time.strftime('%Y-%m-%d', st) '2015-10-22'
>>> time.mktime(st) 1445495655.0 时间字符串转 >>> time.strptime('2015-10-22','%Y-%m-%d') time.struct_time(tm_year=2015, tm_mon=10, tm_mday=22, tm_hour=0, tm_min=0, tm_sec=0, tm_wday=3, tm_yday=295, tm_isdst=-1) 与时间有关的系统调用,如 datetime 模块datetime模块提供对时间和日期的封装,并提供他们之间的数学运算。 object timedelta # 主要用于计算时间跨度 tzinfo # 时区相关 time # 只关注时间 date # 只关注日期 datetime # 同时有时间和日期 date只包含年月日3个属性,datetime还包含时、分、秒、毫秒。 获取现在时间 >>> datetime.today() datetime.datetime(2015, 10, 22, 15, 8, 54, 88000) >>> datetime.now() datetime.datetime(2015, 10, 22, 15, 8, 41, 304000) 与时间戳的转换 >>> datetime.fromtimestamp(ts) datetime.datetime(2015, 10, 22, 14, 34, 15, 495000) 利用 >>> dt = datetime.strptime('2015-10-12','%Y-%m-%d') >>> dt datetime.datetime(2015, 10, 12, 0, 0) >>> dt.strftime('%d/%m/%Y') '12/10/2015' 对datetime对象做部分修改 >>> dt.replace(year=2016) datetime.datetime(2016, 10, 12, 0, 0) 转换为timetuple也就是time.struct_time >>> dt.timetuple time.struct_time(tm_year=2015, tm_mon=10, tm_mday=12, tm_hour=0, tm_min=0, tm_sec=0, tm_wday=0, tm_yday=285, tm_isdst=-1)
timedelta = datetime - datetime datetime = datetime + timedelta 例如 >>> delta = timedelta(hours=1) >>> delta datetime.timedelta(0, 3600) >>> >>> dt + delta datetime.datetime(2015, 10, 12, 1, 0) calendar 模块这个模块主要提供日历的一些操作,可以很方便生成一个文本日历。 >>> print calendar.month(2015,10) October 2015 Mo Tu We Th Fr Sa Su 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 calendar包含一个 总结时间模块的比较: created in 2015-10-22 20:00
|
| You are visitor 01402775 — GeezerVison does not store the pages you look up. Best viewed with Netscape Navigator 4.7 or Internet Explorer 6 at 800×600. No cookies required. |