您的位置:首页 > 编程语言 > Python开发

Python标准库 - time module

2016-03-26 22:36 711 查看
#coding=utf-8

import time

# 另种时间格式: 1.从Epoch开始记的秒数,类似Unix时间戳 2.9个integer的tuple, structtime
# The tuple items are:
#   year (four digits, 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)

##########################
# timestamp与tuple互相转换
cur_timestamp = time.time()  # 当前时间。
# >>>格式:时间戳,1459001151.0

cur_timetuple = time.localtime(cur_timestamp)
# 1: 从时间戳转换为tuple(当地时间)
# 2:不传入参数时,返回当前时间的tuple(当地时间)
# >>> time.struct_time(tm_year=2016, tm_mon=3, tm_mday=26, tm_hour=21, tm_min=55, tm_sec=30, tm_wday=5, tm_yday=86, tm_isdst=0)

cur_timetuple =  time.gmtime(cur_timestamp)
# 1: 从时间戳转换为tuple, UTC (a.k.a. GMT).
# 2:不传入参数时,返回当前时间的tuple, UTC (a.k.a. GMT).

time.mktime(cur_timetuple)  # 从tuple转为timestamp
# >>> 1459001151.0

###################
# string与tuple转换
timetuple = time.strptime("2016-03-26", "%Y-%m-%d") # Parse the string, according to "%Y-%m-%d" format
# >>> time.struct_time(tm_year=2016, tm_mon=3, tm_mday=26, tm_hour=0, tm_min=0, tm_sec=0, tm_wday=5, tm_yday=86, tm_isdst=-1)

string = time.strftime("%Y-%m-%d %H:%M:%S", timetuple)  # convert the tuple into a string, according to "%Y-%m-%d %H:%M:%S" format
# >>> 2016-03-26 00:00:00

##############
# 其他function
seconds = 10.0
time.sleep(seconds=seconds)  # delay execution for seconds
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: