常用的时间操作

print("====================time开始=======================")
import time

# 获取当前时间戳
sec_timestamps = time.time()
years = 1970 + sec_timestamps / (365 * 24 * 3600)
print(years)
# 获取时间元祖
ret = time.localtime(0)
ret1 = time.localtime()
print(ret1)

print(time.ctime(time.time()))
# 将时间元祖转换成指定格式
print(time.strftime("%Y-%m-%d %H:%M:%S", time.localtime()))
# 格式化日期转换成时间元祖
tuple_time = time.strptime("2019-03-25 21:32:59", "%Y-%m-%d %H:%M:%S")
print(tuple_time)
# 时间元祖转换成时间戳
print(time.mktime(tuple_time))
# 测试一段程序的运行时间
start = time.clock()
for i in range(10000):
    if i == 9999:
        break
end = time.clock()
print(end - start)

# 休眠n秒
time.sleep(10)

print("====================time结束=======================")
print("====================calenda开始=======================")
import calendar

# print(calendar.month(2019, 3))
print("====================calenda结束=======================")
print("====================datetime开始=======================")
import datetime

t = datetime.datetime.now()
print(t)
print(t.year)
print(t.month)
print(t.day)
print(t.hour)
print(datetime.datetime.today())

print("====================datetime结束=======================")
print("====================计算n天之后的日期开始=======================")
t = datetime.datetime.today()
t1 = t + datetime.timedelta(days=7)
print(t, t1)

print("====================计算n天之后的日期结束=======================")
print("====================计算时间差开始=======================")
first = datetime.datetime(2018, 8, 8, 8, 8, 8)
second = datetime.datetime(2018, 8, 9, 8, 8, 8)
diff = second - first
print(diff, diff.total_seconds())
print("====================计算时间差结束=======================")

你可能感兴趣的:(常用的时间操作)