Python基础——常用的内置模块-time
time模块
提供各种操作时间的函数
时间的表示方式:
时间戳(相对于1970.1.1 00:00:00以秒计算的偏移量)
结构化时间:包含9个元素
year (including century, e.g. 2018)
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)
常用的函数
time() – 返回时间戳
sleep() – 延迟运行单位为s
gmtime() – 转换时间戳为时间元组(时间对象)
localtime() – 转换时间戳为本地时间对象
asctime() – 将时间对象转换为字符串
ctime() – 将时间戳转换为字符串
mktime() – 将本地时间转换为时间戳
strftime() – 将时间对象转换为规范性字符串
常用的格式代码:
%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.
strptime() – 将时间字符串根据指定的格式化符转换成数组形式的时间
-*- coding:utf-8 -*-
import time
#返回当前时间戳
print(time.time()) #1560783875.6855807
#返回当前时间
print(time.ctime()) #Mon Jun 17 23:04:35 2019
#运行延迟3s
time.sleep(3)
#转换时间戳为时间元组(国际时间)
print(time.gmtime())#time.struct_time(tm_year=2019, tm_mon=6, tm_mday=17, tm_hour=15, tm_min=4, tm_sec=38, tm_wday=0, tm_yday=168, tm_isdst=0)
#本地时间(东八区时间)和格林尼治时间相差8小时
print(time.localtime())#time.struct_time(tm_year=2019, tm_mon=6, tm_mday=17, tm_hour=23, tm_min=13, tm_sec=36, tm_wday=0, tm_yday=168, tm_isdst=0)
#将时间元组转换成时间戳
print(time.mktime(time.localtime()))#1560784616.0
#将时间元组转换成指定的字符串格式
print(time.strftime("%Y-%m-%d %H:%M:%S %A",time.localtime())) #2019-06-17 23:22:32 Monday
#将字符串格式的时间转换成指定的时间元组格式
print(time.strptime("2019-6-17","%Y-%m-%d"))
上一篇: 蜂蜜腌牛油果的制作方法,你真的会吗