一、time模块

三种格式
时间戳时间:浮点数 单位为秒
时间戳起始时间:
1970.1.1 0:0:0 英国伦敦时间
1970.1.1 8:0:0 我国(东8区)
结构化时间:元组(struct_time)
格式化时间:str数据类型的

 

1、常用方法

import time

time.sleep(secs)   推迟指定的时间运行,单位是秒

for i in range(3):
    time.sleep(1)
    print(i)

 

2、表示时间的三种方式

时间戳(timestamp)、元组(struct_time)、格式化(str_time)的时间字符串

1. 时间戳(timestamp) :通常来说,时间戳表示的是从1970年1月1日00:00:00开始按秒计算的偏移量。
我们运行“type(time.time())”,返回的是float类型。
print(time.time())  # 1536050072.5732844(1970年1月1日00:00:00到此刻运行time.time()的时间) 


2. 结构化时间(struct_time) :struct_time元组共有9个元素共九个元素:(年,月,日,时,分,秒,一周中第几天,一年中第几天,夏令时)
struct_time = time.localtime()  # 我国的时间
print(struct_time) 
# time.struct_time(tm_year=2018, tm_mon=9, tm_mday=4, tm_hour=16, tm_min=40, tm_sec=1, tm_wday=1, tm_yday=247, tm_isdst=0)


struct_time = time.gmtime()  # 伦敦的时间
print(struct_time) 
# time.struct_time(tm_year=2018, tm_mon=9, tm_mday=4, tm_hour=8, tm_min=40, tm_sec=1, tm_wday=1, tm_yday=247, tm_isdst=0)


3. 格式化时间(Format_string):
fmt1 =time.strftime('%H:%M:%S')   # 时分秒(全大写)
fmt2 =time.strftime('%Y-%m-%d')   # 年月日(年可大写可小写,月日小写)
fmt3 =time.strftime('%y-%m-%d')   # 年月日
fmt4 =time.strftime('%c')         # 本地相应的日期表示和时间表示

print(fmt1)  # 16:49:03
print(fmt2)  # 2018-09-04
print(fmt3)  # 18-09-04
print(fmt4)  # Tue Sep  4 16:49:03 2018

 

3、几种时间格式间的转换

时间模块和时间工具

1. 转换

Timestamp ---> struct_time: time.localtime(转成我国的时间)、time.gmtime(转成伦敦时间)
struct_time ---> Timestamp: time.mktime()

Format_string ---> struct_time: time.strptime()
struct_time ---> Format_string: time.strftime()

 

2. 例子

1. 把格式化时间2018年8月8日转成时间戳时间
str_time = '2018-8-8'
struct_time = time.strptime(str_time,'%Y-%m-%d')
print(struct_time)  # time.struct_time(tm_year=2018, tm_mon=8, tm_mday=8, tm_hour=0, tm_min=0, tm_sec=0, tm_wday=2, tm_yday=220, tm_isdst=-1)
timestamp = time.mktime(struct_time)
print(timestamp)   # 1533657600.0


2. 把时间戳时间转成格式化时间
timestamp = 1500000000
struct_time = time.localtime(timestamp)
str_time = time.strftime('%Y-%m-%d',struct_time)
print(str_time)   # 2017-07-14


3. 写函数,计算本月1号的时间戳时间
通过我拿到的这个时间,能迅速的知道我现在所在时间的年 月
def get_timestamp():
    str_time = time.strftime('%Y-%m-1')
    struct_time = time.strptime(str_time,'%Y-%m-%d')
    timestamp = time.mktime(struct_time)
    return timestamp
ret = get_timestamp()
print(ret)
%y 两位数的年份表示(00-99%Y 四位数的年份表示(0000-9999%m 月份(01-12%d 月内中的一天(0-31%H 24小时制小时数(0-23%I 12小时制小时数(01-12%M 分钟数(00-59%S 秒(00-59%a 本地简化星期名称

%A 本地完整星期名称

%b 本地简化的月份名称

%B 本地完整的月份名称

%c 本地相应的日期表示和时间表示

%j 年内的一天(001-366%p 本地A.M.或P.M.的等价符

%U 一年中的星期数(00-53)星期天为星期的开始

%w 星期(0-6),星期天为星期的开始

%W 一年中的星期数(00-53)星期一为星期的开始

%x 本地相应的日期表示

%X 本地相应的时间表示

%Z 当前时区的名称

%% %号本身
3. python中时间日期格式化符号

相关文章:

  • 2022-02-15
  • 2021-10-25
  • 2021-08-18
  • 2021-08-17
  • 2021-07-19
  • 2021-09-23
猜你喜欢
  • 2022-01-15
  • 2021-04-09
  • 2021-04-29
相关资源
相似解决方案