Python标准库模块之time

import time

# 返回当前时间戳(1970年后经过的浮点秒数)  时间戳是计算机世界中的时间
# 1555579087.1666212
print(time.time())

# 时间戳-->时间元组(年,月,日,时,分,秒,星期,一年中的第几天 夏令时)
print(time.localtime())   # 若没有参数,则使用当前本地时间戳作为参数
print(time.localtime(1555579087.1666212))
print(time.gmtime())  # 将当前的UTC作为参数
print(time.gmtime(1555579087.1666212))

# 时间元组-->时间戳
# 时间元组共有9组数字, 分别代表:年、月、日、时、分、秒、一年中的第几周、一年中的第几天、是否为夏令时
print(time.mktime(time.localtime()))
print(2019, 7, 20, 10, 28, 40, 8, 36, 0)
# 时间元组是结构化的时间或完整的9位元组元素,若元组值不合法,会触发OverflowError或ValueError异常

# 时间元组-->字符串  (时间的格式化)
print(time.strftime("%Y %m %d  %H %M %S", time.localtime()))
# 将时间转换为固定格式的字符串,字符串的格式为“星期 月份 日 时:分:秒 年份”
print(time.asctime(time.localtime(time.time())))

# 时间戳-->字符串
# print(time.ctime())  # 相当于asctime(localtime())

# 字符串 --> 时间元组
print(time.strptime("2018 9 10", "%Y %m %d"))

# 实例:
# 1:定义函数,输入年月日,返回星期几
# 2:定义函数,根据生日返回活了多少天
#     (根据年月日构建时间元组,根据构建的时间元组获取时间戳,
#     使用当前时间戳减去生日时间戳,将秒数换算成为天数)

def get_weekday(year, month, day):
   time_tuple = time.strptime(year + " " + month + " " + day, "%Y %m %d")
   weeks = {
      0: "星期一",
      1: "星期二",
      2: "星期三",
      3: "星期四",
      4: "星期五",
      5: "星期六",
      6: "星期天"
   }
   # 从时间元组中获取星期数
   return weeks[time_tuple[6]]


# year = input("请输入年:")
# month = input("请输入月:")
# day = input("请输入日:")
# print(get_weekday(year, month, day))

def get_life_days(year, month, day):
   time_tuple = time.strptime(year + " " + month + " " + day, "%Y %m %d")
   life_seconds = time.time() - time.mktime(time_tuple)
   return life_seconds // 3600 // 24


print(get_life_days("2009", "12", "05"))
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 2
    评论
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值