目录
引言
“时间”是我们在进行数据分析时十分重要的维度,比如日期、分时,因此在初学python时,学会与“时间”相处是我们的必修课,这就要学习python中两个非常重要的处理时间的库——time
和datetime
。
import time,datetime
为了控制篇幅,我将分两期介绍python中常用的处理时间的函数,涵盖的知识点大致如下:
- 常见的时间格式
- 不同时间格式的相互转换
%
的使用 - 时间信息提取
比如:某一日期是星期几、一年中的第几天、一年中的第几周 ;提取时间中的年、月、日 ··· - 时间计算
比如:两个日期间隔的天数、获取日期前(后)N天的日期 ··· - 时间生成
比如:生成两个日期之间的所有日期、生成各月末的日期 ···
本文首先介绍python中常见的时间格式和不同时间格式的相互转换。
Let’s get started!
一、常见的时间格式
我将直接通过代码向大家演示python常见的时间格式都长啥样,并且分别包含了哪些信息:
float型时间戳 (timestamp)
time.time()
返回当前时间,格式为float型时间戳 (timestamp),其数字含义是纪元(通常是1970年1月1日)以来的秒数。
time.time() #float型时间戳
>>>1595645325.6948063
There are two standard representations of time. One is the number of seconds since the Epoch, in UTC (a.k.a. GMT). It may be an integer or a floating point number (to represent fractions of seconds).
The Epoch is system-defined; on Unix, it is generally January 1st, 1970.
time.struct_time — a tuple of 9 integers
time.localtime()
返回当前时间,格式为time.struct_time时间格式,它是一个包含了9个数字的tuple,这9个数字的含义如下:
- year (including century, e.g. 1998)
- month (1-12)
- day (1-31)
- hours (0-23)
- minutes (0-59)
- seconds (0-59)
- weekday (0-6, Monday is 0)
- Julian day (day in the year, 1-366)
- DST (Daylight Savings Time) flag (-1, 0 or 1)
If the DST flag is 0, the time is given in the regular time zone;
if it is 1, the time is given in the DST time zone;
if it is -1, mktime() should guess based on the date and time.
time