Python3 日期时间 相关模块(time(时间) / datatime(日期时间) / calendar(日历))
本文由 Luzhuo 编写,转发请保留该信息.
原文: http://blog.youkuaiyun.com/Rozol/article/details/71307483
以下代码以Python3.6.1为例
Less is more!
#!/usr/bin/env python
# coding=utf-8
__author__ = 'Luzhuo'
__date__ = '2017/5/5'
# timedemo.py 时间相关的模块演示
# 演示的模块:time(时间) / datatime(处理 日期&时间) / calendar(日历)
import time
def time_demo():
curtime = time.time() # 获取当前时间戳
time_str = time.ctime(curtime) # 转为string格式
print(time_str) # => Fri May 5 18:28:08 2017
time_tup = time.localtime(curtime) # 转为struct_time(tuple)格式
print(time_tup.tm_year) # => 2017
def time_func():
'''
time模块处理时间的相关说明:
1. 部分系统无法处理很久之前或之后的日期和时间 (如:32系统通常时间到2038年为止)
2. UTC (/GMT) 为格林威治标准时间 (简称:世界时间);
3. DST 为夏令时
4. 格式化指示符: %Y(世纪年) / %m(月[01, 12]) / %d(日[01, 31]) / %H(时[00, 23]) / %M(分[00, 59]) / %S(秒[00, 61]) / %w(星期[0, 6])
%b(月E缩写) %B(月E) / %a(星期E缩写) / %A(星期E) / %I(12时[01, 12]) / %c(日期+时间) / %x(日期) / %X(时间) / %p(AM/PM) / %z(时区[-23:59,+23:59]) / %%('%')
%j(年<-日[001, 366]) / %U(年<-星期[00, 53]) / %W(年<-周[00, 53])
5. 星期日为一个星期周期的第一天
'''
# 时间戳
time_s = time.altzone # 夏令时与UTC的差值
time_s = time.timezone # (时区) 本地时间与UTC的差值
time_s = time.time() # 当前时间戳 (受系统时间影响) 单位:秒 ( => 1493986228.8606732 >> 1493986228s)
time_s = time.mktime(time_tup) # 元组转成时间
time_s = time.monotonic() # 单调始终的值 (不受系统时钟更新的影响) 单位:秒 ( => 250075.796 >> 250075s)
time_s = time.perf_counter() # (高分辨率)性能计数器 (包括睡眠时间) 单位:秒 ( => 552.1569544781966 >> 552s)
# 元组(struct_time) [格式:(2008, 1, 1, 0, 0, 0, -1, -1, -1) >> (年, 月, 日, 时, 分, 秒, 星期, 年<-日, DST)]
# gmtime([secs]) // 时间戳转为UTC; 0: 开始0年的时间(1970年) / 无参:UTC / time_s:转为世界时间
time_tup = time.gmtime(time_s)
# localtime([secs]) // 时间戳转为本地时间
time_tup = time.localtime(time_s)
# strptime(string[, format]) 解析时间
time_tup = time.strptime('Tue Jan 01 00:00:00 2008', '%a %b %d %H:%M:%S %Y') # 字符串解析成时间
# struct_time
time_year = time_tup.tm_year # 从struct_time中获取数据, 其他省略
# 字符串
# asctime([t]) // 时间格式化 (系统样式); 不传参为当前时间
time_str = time.asctime(time_tup)
# ctime([secs]) // 同asctime()
time_str = time.ctime(time_s)
# strftime(format[, t])
time_str = time.strftime("%Y-%m-%d-%H-%M-%S", time_tup)
# 其他
time.sleep(1.1) # 线程睡眠 单位:s
time_dst = time.daylight # 夏令时时区(0未定义)
# ===========================================
import datetime
def datetime_demo():
datetime_dt = datetime.datetime.today() # 获取当前日期和时间</