时间模块

时间模块

时间戳
  • 获取时间戳

    import time
    
    int(time.time())
    
  • 时间戳 转 datetime

    from datetime import datetime
    
    datetime.fromtimestamp(int(time.time()))
    
    # 2022-03-27 12:33:03
    
  • 时间戳 ==》字符串

    # 核心方法:strftime()  time、datetime两个模块均有此方法
    
    # time 模块:
    time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(timestamp))
    
    # timedatetime 模块:
    datetime.utcfromtimestamp(timestamp).strftime("%Y-%m-%d %H:%M:%S")  # 注意此方法的时区问题
    datetime.fromtimestamp(timestamp).strftime("%Y-%m-%d %H:%M:%S")
    
    # 结果都是:2022-03-27 12:44:22
    

获取当前时间
  1. 获取当前时间:

    • 时间戳

      int(time.time()
      
    • 字符串

      datetime.now().strftime("%Y-%m-%d %H:%M:%S")       # 2022-05-30 18:16:59
      return time.strftime("%Y-%m-%d %X")                # 2022-05-30 18:18:07
      

时间加减
# datetime对象,可以加上timedelta对象,得到的是datetime对象
from datetime import datetime, timedelte

new_time = datetime.now() + timedelta(days=10)
new_time = datetime.now() + timedelta(days=-10)
new_time = datetime.now() + timedelta(hours=10)
new_time = datetime.now() + timedelta(hours=-10)
new_time = datetime.now() + timedelta(seconds=120)
获取时间间隔
def get_time_interval(start, end=None):

    if not end:  # 截止到此时此刻
        time_interval = datetime.now() - datetime.strptime(start, "%Y-%m-%d %H:%M:%S")
    else:
        time_interval = datetime.strptime(end, "%Y-%m-%d %H:%M:%S") - datetime.strptime(start, "%Y-%m-%d %H:%M:%S")
    time_interval = int(time_interval.total_seconds() / (60 * 60 * 24))
    return time_interval
获取月份
from datetime import datetime, timedelta


def get_months(months):
    start_month = datetime.strptime(months[0], "%Y-%m")
    end_month = datetime.strptime(months[1], "%Y-%m")
    if start_month == end_month:
        return [start_month.strftime('%Y-%m')]
    months = []
    while True:
        if start_month < end_month:
            start_month += timedelta(days=27)
            if start_month.strftime('%Y-%m') not in months:
                months.append(start_month.strftime('%Y-%m'))
        else:
            break
    return months


months = get_months(['1992-6', '2022-06'])

print(len(months), months)
posted @ 2019-12-12 23:14  疯狂列表推导式  阅读(137)  评论(0编辑  收藏  举报