关于python中datetime模块的用法

datetime模块

datetime模块属于Python标准库,用来处理时间和日期。

官方文档: https://docs.python.org/3.6/library/datetime.html

先看一个练习题:

有一类文件,文件名为 output_1981.10.21.txt 这种格式。
要求使用Python 读取文件名中的日期时间信息,并找出这一天是星期几,并将文件改名为output_YYYY-MM-DD-W.txt
W:星期几(1-7), 星期一对应’1’, 星期天对应’7’

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
import re
from datetime import datetime

file_name = 'output_1981.10.21.txt'

res = re.match(r'(\w+_)(\d{4}\.\d{2}\.\d{2})(\.\w+)', file_name)

if res:
f_class = res.group(1) # output_
f_date = res.group(2) # 1981.10.21
f_format = res.group(3) # .txt
else:
print("File not found!")
# for test
print("The file name is %s + %s + %s" % (f_class, f_date, f_format))

date_li = f_date.split(".")
f_year = int(date_li[0]) # 1981 int
f_month = int(date_li[1]) # 10 int
f_day = int(date_li[2]) # 21 int

# 调用datetime模块下的datetime(), 依次传入年,月,日(类型必须为int),可以返回一个时间类型 <class 'datetime.datetime'>
# 再调用.strftime("%w")将时间类型转换为str,并得到对应是星期几
week = datetime(f_year, f_month, f_day).strftime("%w")
print(week) # 3 <class 'str'>

# 默认星期天对应数字0
if week == "0":
week = "7"
else:
week = str(week)

new_f_date = f_date + '.' + week # 1981.10.21.3
new_file_name = f_class + new_f_date + f_format
print(new_file_name) # output_1981.10.21.3.txt

datatime.strftime(format) 格式化

Return a string representing the date and time, controlled by an explicit format string.

返回一个表示日期和时间的字符串,由一个明确的格式化字符串控制(即传入的参数).

具体传入参数对应的返回值格式如下:

Directive Meaning Example Notes
%a Weekday as locale’s abbreviated name. Sun, Mon, …, Sat (en_US);So, Mo, …, Sa (de_DE) (1)
%A Weekday as locale’s full name. Sunday, Monday, …, Saturday (en_US);Sonntag, Montag, …, Samstag (de_DE) (1)
%w Weekday as a decimal number, where 0 is Sunday and 6 is Saturday. 0, 1, …, 6
%d Day of the month as a zero-padded decimal number. 01, 02, …, 31
%b Month as locale’s abbreviated name. Jan, Feb, …, Dec (en_US);Jan, Feb, …, Dez (de_DE) (1)
%B Month as locale’s full name. January, February, …, December (en_US);Januar, Februar, …, Dezember (de_DE) (1)
%m Month as a zero-padded decimal number. 01, 02, …, 12
%y Year without century as a zero-padded decimal number. 00, 01, …, 99
%Y Year with century as a decimal number. 0001, 0002, …, 2013, 2014, …, 9998, 9999 (2)
%H Hour (24-hour clock) as a zero-padded decimal number. 00, 01, …, 23
%I Hour (12-hour clock) as a zero-padded decimal number. 01, 02, …, 12
%p Locale’s equivalent of either AM or PM. AM, PM (en_US);am, pm (de_DE) (1), (3)
%M Minute as a zero-padded decimal number. 00, 01, …, 59
%S Second as a zero-padded decimal number. 00, 01, …, 59 (4)
%f Microsecond as a decimal number, zero-padded on the left. 000000, 000001, …, 999999 (5)
%z UTC offset in the form +HHMM or -HHMM (empty string if the object is naive). (empty), +0000, -0400, +1030 (6)
%Z Time zone name (empty string if the object is naive). (empty), UTC, EST, CST
%j Day of the year as a zero-padded decimal number. 001, 002, …, 366
%U Week number of the year (Sunday as the first day of the week) as a zero padded decimal number. All days in a new year preceding the first Sunday are considered to be in week 0. 00, 01, …, 53 (7)
%W Week number of the year (Monday as the first day of the week) as a decimal number. All days in a new year preceding the first Monday are considered to be in week 0. 00, 01, …, 53 (7)
%c Locale’s appropriate date and time representation. Tue Aug 16 21:30:00 1988 (en_US);Di 16 Aug 21:30:00 1988 (de_DE) (1)
%x Locale’s appropriate date representation. 08/16/88 (None);08/16/1988 (en_US);16.08.1988 (de_DE) (1)
%X Locale’s appropriate time representation. 21:30:00 (en_US);21:30:00 (de_DE) (1)
%% A literal '%' character. %

详见https://docs.python.org/3.6/library/datetime.html#strftime-strptime-behavior

datetime对象

datetime模块下的datetime对象的构造方法为:

class datetime.datetime(year, month, day[, hour[, minute[, second[, microsecond[, tzinfo]]]]])

year, month 和 day 参数是必须的,其他参数可选, 参数tzinfo表示可选的时区信息,一般我们也用不到。参数值的范围如下:

  • MINYEAR <= year <= MAXYEAR
  • 1 <= month <= 12
  • 1 <= day <= number of days in the given month and year
  • 0 <= hour < 24
  • 0 <= minute < 60
  • 0 <= second < 60
  • 0 <= microsecond < 1000000

例:

1
2
3
4
5
6
7
8
from datetime import datetime
t = datetime(2015, 8, 23, 15, 12, 59)
print(t)
print(type(t))

输出:
2015-08-23 15:12:59
<class 'datetime.datetime'>

如果我们只传入参数year, month, day, 则返回结果为:

1
2015-08-23 00:00:00

下面我们看下datetime对象的几个方法:

datetime.today() 返回本地当前的时间

1
2
3
4
5
from datetime import datetime
print("当前时间: %s" % datetime.today())

输出:
当前时间: 2018-07-22 15:19:21.932494

datetime.now([tz]) 返回本地当前的日期和时间。如果可选的参数 tz 为 None 或者没有指定,结果同today()

tz参数为时区参数

1
"Construct a datetime from time.time() and optional time zone info."
1
2
3
4
5
6
7
8
9
10
11
12
13
from datetime import datetime
import pytz

print("当前时间: %s" % datetime.now())
Shanghai = pytz.timezone('Asia/Shanghai')
Eastern = pytz.timezone('US/Eastern')
print("当前时间: %s" % datetime.now(tz=Shanghai))
print("东部标准时间: %s" % datetime.now(tz=Eastern))

输出:
当前时间: 2018-07-22 15:20:28.522964
当前时间: 2018-07-22 15:43:14.152172+08:00
东部标准时间: 2018-07-22 03:43:14.152172-04:00

datetime对象还有两个属性:min和max

1
2
3
4
5
6
7
8
9
from datetime import datetime
min_time = datetime.min
max_time = datetime.max
print(min_time)
print(max_time)

输出:
0001-01-01 00:00:00
9999-12-31 23:59:59.999999

datetime模块的对象有如下:

  • timedelta
  • date
  • datetime
  • time
  • tzinfo

有时间再来更新其他对象的用法…

本文标题:关于python中datetime模块的用法

文章作者:Vincent Zheng

发布时间:2018年07月22日 - 15:07

最后更新:2018年07月22日 - 16:07

原始链接:https://zws910.github.io/2018/07/22/datetime-module/

许可协议: 署名-非商业性使用-禁止演绎 4.0 国际 转载请保留原文链接及作者。

0%