datetime

模块介绍

The datetime module supplies classes for manipulating dates and times in both simple and complex ways. While date and time arithmetic is supported, the focus of the implementation is on efficient attribute extraction for output formatting and manipulation.


Class介绍

类列表

  • date

date

源码说明

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
class date:
"""Concrete date type.

Constructors:

__new__()
fromtimestamp()
today()
fromordinal()

Operators:

__repr__, __str__
__eq__, __le__, __lt__, __ge__, __gt__, __hash__
__add__, __radd__, __sub__ (add/radd only with timedelta arg)

Methods:

timetuple()
toordinal()
weekday()
isoweekday(), isocalendar(), isoformat()
ctime()
strftime()

Properties (readonly):
year, month, day
"""

获取今天日期

1
2
3
4
import datetime

today = datetime.date.today()
print(today)

输出 2017-10-13

固定格式,格式化时间戳

1
2
3
4
5
6
7
8
9
10
11
import time
import datetime

timestamps = time.time()
print("timestamps:", timestamps, type(timestamps))
print("timestamps:", int(timestamps), type(int(timestamps)))

today = datetime.date.fromtimestamp(timestamps)
print("today from float type:", today)
today = datetime.date.fromtimestamp(int(timestamps))
print("today from int type:", today)

输出

1
2
3
4
timestamps: 1507898957.5218294 <class 'float'>
timestamps: 1507898957 <class 'int'>
today from float type: 2017-10-13
today from int type: 2017-10-13

可选格式,格式化时间

常用时间格式参数

  • %y 年份,0-99之间
  • %Y 年份的完整拼写
  • %m 月份,01-12之间
  • %d 日期数,1-31之间
  • %H 小时数,00-23之间
  • %M 分钟数,01-59之间
  • %S 秒数
  • %X 本地的当前时间

  • %a 英文星期的简写

  • %A 英文星期的完整拼写
  • %b 英文月份的简写
  • %B 英文月份的完整拼写
  • %c 本地当前的日期与时间
  • %I 小时数,01-12之间
  • %j 本年从第1天开始计数到当天的天数
  • %w 星期数,0-6之间(0是周日)
  • %W 当天属于本年的第几周,周一作为一周的第一天进行计算
  • %x 本地的当天日期
示例代码1
1
2
3
date_instance = datetime.date(2017, 10, 13)
print(date_instance)
print(date_instance.strftime("%y-%m-%d %X"))

输出结果

1
2
2017-10-13
17-10-13 00:00:00


示例代码2
1
2
3
4
timestamps = time.time()
today = datetime.date.fromtimestamp(timestamps)
print(today.strftime("%Y-%m-%d %H:%M:%S"))
print(today.strftime("%Y-%m-%d %X"))

输出结果

1
2
2017-10-13 00:00:00
2017-10-13 00:00:00

计算当前日期第几周

1
2
3
4
5
date_instance = datetime.date(2017, 10, 13)
print(date_instance.weekday())
print(date_instance.isoweekday())
# year, week number, and weekday
print(date_instance.isocalendar())

输出结果

1
2
3
4
5
(2017, 41, 5)

time

源码说明

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
class time:
"""Time with time zone.

Constructors:

__new__()

Operators:

__repr__, __str__
__eq__, __le__, __lt__, __ge__, __gt__, __hash__

Methods:

strftime()
isoformat()
utcoffset()
tzname()
dst()

Properties (readonly):
hour, minute, second, microsecond, tzinfo, fold
"""