0%

Python-时间日期

Python 在时间日期方面的最佳实践。如:

  • time:【标准库】基本时间日期操作
  • datetime:【标准库】time 的升级款,更倾向于成员提取以进行输出格式化与操作、感知时区。
  • calendar:【标准库】日历

概述

时间类型

时间戳

timestamp:时间戳,float 类型,1970 年 1 月 1 日 00:00:00 开始的按秒的时间偏移量 (float)

1
(time.time()/60/60/24/365)//1+1970  # 2018 年

struct_time

struct_time:结构化时间对象元组,time.struct_time 类型

1
2
3
4
5
6
7
8
9
time.localtime().tm_year  # 年
time.localtime().time.localtime.tm_mon # 月:1-12
time.localtime().tm_day # 日:1-31
time.localtime().tm_hour # 时:0-23
time.localtime().tm_min # 分钟 0-59
time.localtime().tm_sec # 秒 0-59
time.localtime().tm_wday # 一周的第几天,周一为 0,周日为 6
time.localtime().tm_yday # 一年的第几天
time.localtime().tm_isdst # 是否为夏令时

FormatString

FormatString:格式化时间字符串:

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
32
33
34
35
36
37
38
39
# 数字均为十进制,大多以 0 补足两位
%Y 完整的年份
%y 年(后两位数字,以 0 补足两位)

%m 月份,[01,12]
%b 月份的简写 4 月为 Apr
%B 月份的全称 4 月为 April

%d 日期,[01,31].
%H 24 小时制的小时[00,23].
%M 分钟,[00,59].
%S 秒[00,61].
%f 微秒(以 0 补足六位)

%z 相对 UTC 时区偏移量,(格式是 ±HHMM[SS],未指定时区则返回空字符串)'+1030'
%Z 时区名(未指定时区则返回空字符串)
%a 星期几的简写 周三为 Web
%A 星期几的全称 周三为 Wednesday
%w 星期几(数字,0 是周日,6 是周六)
%u 星期几(数字,1 是周一,7 是周日)


%c 标准的日期时间串 (04/07/10 10:43:39)
%F 年-月-日
%x or %D 本地标准日期串,'05/14/19'
%X 本地标准时间串,'14:24:24'
%T 显示时分秒:hh:mm:ss

%I 12 小时制的小时[01,12].
%p 上午 下午 AM or PM.

%u 每周的第几天,星期一为第一天 (值从 06,星期一为 0
%U 第年的第几周,把星期日做为第一天(值从 053
%U 一年中的第几周(以全年首个周日后的星期为第 0 周,以 0 补足两位)
%V 每年的第几周,使用基于周的年,一年中的第几周(以全年首个包含 14 日的星期为第 1 周,以 0 补足两位)
%W 每年的第几周,星期一为第一天(0-53
%w 一个星期中的第几天(0-6)星期天为 6
%j 一年中的第几天(以 0 补足三位)
%e 在两字符域中,十进制表示的每月的第几天

time

time:【标准库】基本时间日期操作

获取

1
2
3
4
5
6
7
8
9
10
11
# timestamp
time.time()

# struct_time
time.gmtime() # 格林威治 UTC 时区的当前 struct_time,与本地差 8 小时
time.localtime() # 本地时间
# time.struct_time(tm_year=2018, tm_mon=11, tm_mday=22, tm_hour=14, tm_min=28, tm_sec=0, tm_wday=3, tm_yday=326, tm_isdst=0)

# FormatString
time.ctime() # 将一个秒数时间戳表示为字符串,无参数时使用 time.time()
time.asctime() # 将 tuple 或 struct_time 转为 24 个字符的时间字符串,格式为: "Fri Aug 19 11:14:16 2016",无参数时使用 time.localtime()

其他

1
2
time.altzone # 与 utc 时间的时间是差,单位为秒,西区为正,东区为负
time.clock() # 当前进程占用处理器运行的秒数(不包括 sleep 时间)

转换

1
2
3
4
5
6
7
8
9
10
11

timestamp=time.time() # 获取时间戳
time.localtime(timestamp) # 时间戳 转 struct_time
time.strftime('%Y-%m-%d %H:%M:%S',time.localtime()) # struct_time 转 字符串
time.strptime('2011-12-01 14:15:40','%Y-%m-%d %H:%M:%S') # 字符串 转 struct_time
time.mktime(time.localtime()) # struct_time 转 时间戳

today_date = time.strftime('%Y-%m-%d', time.localtime())
"2021-01-01"
now_timestamp=time.strftime('%Y-%m-%d-%H-%M-%S',time.localtime())+'_'+str(int(time.time()%1*1000))
"2021-01-01-12-30-45-125"

暂停 -sleep

1
2
# time.sleep(sec)
time.sleep(2) # 程序“睡”2 秒

datetime

datetime:【标准库】time 的升级款,更倾向于成员提取以进行输出格式化与操作、感知时区。

  • 需要时区信息才能确定一个特定的时间,否则·只能设定为本地时间
  • 若要存储 datetime,最佳方法是将其转换为 timestamp 再存储,因为 timestamp 的值与时区完全无关。
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
from datetime import datetime

datetime.date() # 日期的类,year,month,day;
datetime.time() # 时间的类,hour,minute,second,microsecond;
datetime.datetime():表示日期时间的类;

datetime.datetime.today()
datetime.datetime.now() # 获取当前时间
datetime.datetime.now().replace(year=2000,month=10,day=1)

datetime(year,month,day,hour=0, minute=0, second=0, microsecond=0, tzinfo=None)

datetime(2019,12,6,13,30,50)
# 输出 : datetime.datetime(2019, 12, 6, 13, 30, 50)
参数范围:

- MINYEAR <= year <= MAXYEAR
- 1 <= month <= 12
- 1 <= day <= 指定年月的天数
- 0 <= hour < 24
- 0 <= minute < 60
- 0 <= second < 60
- 0 <= microsecond < 1000000

转换

时间戳转 datetime

1
datetime.datetime.fromtimestamp(time.time())

转时间戳

1
2
3
4
# 返回指定时间的时间戳使用 mktime
d = datetime.datetime(1997,12,29,15,59,59)
t = d.timetuple()#再转为元组
print(time.mktime(t)) #使用 time 的 mktime 方法返回时间戳

时间操作

1
2
3
4
5
6
7
datetime.timedelta():表示时间间隔,即两个时间点之间的长度;
# 时间运算,加一天
s=datetime.now()+datetime.timedelta(days=1)
s=datetime.now()+datetime.timedelta(minutes=30)
s=datetime.now()+datetime.timedelta(hours=3)
# 时间替换
s.replace(year=2020,month=11,day=30)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
def datetime_filter(t):
delta = int(time.time() - t)
if delta < 60:
return u'1 分钟前'
if delta < 3600:
return u'%s 分钟前' % (delta // 60)
if delta < 86400:
return u'%s 小时前' % (delta // 3600)
if delta < 604800:
return u'%s 天前' % (delta // 86400)
dt = datetime.fromtimestamp(t)
return u'%s 年%s 月%s 日' % (dt.year, dt.month, dt.day)


now=datetime.datetime.now()
now.strftime('%Y-%m-%d %H:%M:%S')
now.strftime('%Y-%m-%d')
now.strftime('%H-%M-%S')

calendar

calendar:【标准库】日历

1
2
3
4
5
6
7
8
9
10
import calendar
print() # 返回指定年月的日历,一个二维列表
calendar.monthrange(year,month) # 传入年份、月份,返回该月第一天所在的星期几及该月一共有多少天
# 用 print 打印出来效果会好些
# 指定年月的日历,一个二维列表
calendar.monthcalendar(2018,11)
# 指定年
calendar.calendar(2020)
# 是否是闰年
calendar.isleap(year)
给博主来一杯卡布奇诺