Python时间模块之datetime

原文地址: https://www.jianshu.com/p/d07a78005d93

不管使用什么语言,时间处理在日常编程中经常会遇到,如:

  1. 获取当前时间
  2. 时间比较
  3. 时间计算
  4. 字符串和时间互转

因此有必要整理下常用处理方法,记录如下.

0. 介绍

datetime: 基础的日期和时间模块. 支持日期和时间的数学运算,但是专注的是时间的格式化和处理。

要注意的是date和time对象有两种类型:naiveaware.

  • naive: 没有关于时区的信息存储
  • aware: 就是指存储了时区信息

datetime模块包含六个子类:

  • date: An idealized naive date,Attributes: year, month, and day.
  • time: An idealized time,Attributes: hour, minute, second, microsecond, and tzinfo.
  • datetime: A combination of a date and a time. Attributes: year, month, day, hour, minute, second, microsecond, and tzinfo.
  • timedelta: A duration expressing the difference between two date, time, or datetime instances to microsecond resolution(微秒).
  • tzinfo: An abstract base class for time zone information objects.
  • timezone: A class that implements the tzinfo abstract base class as a fixed offset from the UTC.
  • 1毫秒=1000微秒

下面介绍4前四个模块

1. timedelta

这个是date,time或datetime同类中间时间差的对象,存储的单位为微秒,相关方法如下:

# 构造方法
datetime.timedelta(days=0, seconds=0, microseconds=0, milliseconds=0, minutes=0, hours=0, weeks=0)
# 返回总秒数
timedelta.total_seconds()

不同类之间不能运算,如date和time就不能运算

2. date

# 构造方法
datetime.date(year, month, day)

# 其他方法和属性
date.today() # 返回当天日期
date.replace(year=self.year, month=self.month, day=self.day)  # 返回一个新的date对象
date.weekday() # 0-6
date.strftime(format) # 日期转字符串

date.year # Between MINYEAR and MAXYEAR inclusive.
date.month # Between 1 and 12 inclusive.
date.day # Between 1 and the number of days in the given month of the given year.

strftime格式化相关参数说明

示例:

>>> datetime.date.today().strftime('%Y %m %d %H %M %S')
'2018 01 26 00 00 00'

支持运算:

date2 = date1 + timedelta   # date2 is timedelta.days days removed from date1. (1)
date2 = date1 - timedelta   # Computes date2 such that date2 + timedelta == date1. (2)
timedelta = date1 - date2   # 相减得到一个timedelta对象
date1 < date2   # date1 is considered less than date2 when date1 precedes date2 in time. (4)

3. time

time对象

datetime.time(hour=0, minute=0, second=0, microsecond=0, tzinfo=None, *, fold=0)

time.replace(hour=self.hour, minute=self.minute, second=self.second, microsecond=self.microsecond, tzinfo=self.tzinfo, * fold=0)
time.strftime(format)

time.hour # In range(24).
time.minute # In range(60).
time.second # In range(60).
time.microsecond # In range(1000000).

4. datetime

是date和time的组合版本.

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

datetime.today()
datetime.now(tz=None)
datetime.strptime(date_string, format) # 字符串转日期
datetime.date() # 返回date对象
datetime.time() # 返回time对象
datetime.weekday()
datetime.strftime(format)
datetime.replace(year=self.year, month=self.month, day=self.day, hour=self.hour, minute=self.minute, second=self.second, microsecond=self.microsecond, tzinfo=self.tzinfo, * fold=0)

datetime.year # Between MINYEAR and MAXYEAR inclusive.
datetime.month # Between 1 and 12 inclusive.
datetime.day # Between 1 and the number of days in the given month of the given year.
datetime.hour # In range(24).
datetime.minute # In range(60).
datetime.second # In range(60).
datetime.microsecond # In range(1000000).

同date一样支持加减运算

示例:

>>> dt = datetime.datetime.strptime('21/11/06 16:30', '%d/%m/%y %H:%M') # 字符串转时间
>>> dt
datetime.datetime(2006, 11, 21, 16, 30)

格式不同则会抛出ValueError异常

5. 常用操作

# 先导入包
>>> import datetime

# 1. 获取当前时间
>>> datetime.datetime.now()
datetime.datetime(2018, 1, 25, 19, 18, 11, 793614)

# 2. 时间比较
>>> t1=datetime.datetime.now()
>>> t2=datetime.datetime.now()
>>> t1>t2
False

# 3. 时间计算
>>> td=t1-t2
>>> td
datetime.timedelta(-1, 86392, 888722)

# 4. 字符串和时间互转
>>> t1.strftime('%Y-%m-%d %H:%M:%S') # 日期转字符串
'2018-01-25 19:18:40'

>>> dt = datetime.datetime.strptime('21/11/06 16:30', '%d/%m/%y %H:%M') # 字符串转时间
>>> dt
datetime.datetime(2006, 11, 21, 16, 30)

6. 时间其他相关处理模块

  1. time: Time access and conversions
  2. calendar: General calendar-related functions
  3. timeit: Measure execution time of small code snippets

Reference

  1. datetime
    原文作者:keith666
    原文地址: https://www.jianshu.com/p/d07a78005d93
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞