Python时间运算的详细机制探讨

本篇为Python时间运算的详细机制探讨,快速运用Python的datetime进行时间运算请参考一句话快速进行python时间运算

我们先来看一张图:

1
import time

下面按照从左至右再至左的顺序分布讲解,首先导入时间模块;

1
2
In [5]: time.strptime('20161009','%Y%m%d')
Out[5]: time.struct_time(tm_year=2016, tm_mon=10, tm_mday=9, tm_hour=0, tm_min=0, tm_sec=0, tm_wday=6, tm_yday=283, tm_isdst=-1)
  • 1 通过time.strptime()将普通字符时间转换为时间元祖,注意这两者在转换时需要指定字符时间的格式(%Y%m%d这里只用到了年月日);
1
2
3
In [6]: time.mktime(time.strptime('20161009','%Y%m%d'))
Out[6]: 1475942400.0
  • 2 通过time.mktime将上一步的时间元祖转换为时间戳,也就是1970年0时0分0秒到20161009的0时0分0秒为止,过了多少秒;
1
2
In [7]: time.localtime(1475942400.0)
Out[7]: time.struct_time(tm_year=2016, tm_mon=10, tm_mday=9, tm_hour=0, tm_min=0, tm_sec=0, tm_wday=6, tm_yday=283, tm_isdst=0)
  • 3 通过 time.mktime将时间戳转换为时间元祖;
1
2
In [13]: time.strftime('%Y%m%d',time.localtime(1475942400.0))
Out[13]: '20161009'
  • 4 通过time.strftime将时间元祖复原为普通字符时间,同样注意需要指定字符时间的格式。

附:字符时间常用格式

1
2
3
4
5
6
7
8
9
10
11
12
13
14
%Y Year with century as a decimal number.
%m Month as a decimal number [01,12].
%d Day of the month as a decimal number [01,31].
%H Hour (24-hour clock) as a decimal number [00,23].
%M Minute as a decimal number [00,59].
%S Second as a decimal number [00,61].
%z Time zone offset from UTC.
%a Locale's abbreviated weekday name.
%A Locale's full weekday name.
%b Locale's abbreviated month name.
%B Locale's full month name.
%c Locale's appropriate date and time representation.
%I Hour (12-hour clock) as a decimal number [01,12].
%p Locale's equivalent of either AM or PM.