python: datetime模块常用

1. datetime.date类的常用方法

# Python中提供了多个用于对日期和时间进行操作的内置模块:time模块、datetime模块和calendar模块。
# time模块是通过调用C库实现的,所以有些方法在某些平台上可能无法调用,但是其提供的大部分接口与C标准库time.h基本一致。
# datetime模块提供的接口更直观、易用,功能也更加强大。
import datetime
import time

# datetime.date类的常用方法
# datetime.date类的生成年月日格式的写法, 今日是2020-09-30 周三
ymd = datetime.date.today()
print(ymd)  # 2020-09-30
print(ymd.strftime('%Y-%m-%d'))  # 2020-09-30
print(ymd.strftime('%Y/%m/%d'))  # 2020/09/30
print(ymd.isoformat())  # 2020-09-30 默认展示这种方式
print(ymd.year, ymd.month, ymd.day)  # 2020 9 30
print(ymd.replace(2020))  # 2020-09-30
print(ymd.replace(2020, 9))  # 2020-09-30
print(ymd.replace(2020, 9, 30))  # 2020-09-30
print(ymd.timetuple())  # time.struct_time(tm_year=2020, tm_mon=9, tm_mday=30, tm_hour=0, tm_min=0, tm_sec=0, tm_wday=2, tm_yday=274, tm_isdst=-1)
print(ymd.weekday())  # 2 周三属于0-6的2
print(ymd.isoweekday())  # 3 周三属于1-7的3
print(ymd.isocalendar())  # (2020, 40, 3) 第40周的第三天
ymd = datetime.date.fromtimestamp(time.time())  # 2020-09-30
print(ymd)
today_ymd_str = datetime.date.today().strftime('%Y-%m-%d')
today_zero_timestamp = int(time.mktime(datetime.date.today().timetuple()))
print('零点字符串', type(today_ymd_str), today_ymd_str)
print('零点时间戳', today_zero_timestamp)
ymd_stamp = int(time.mktime(datetime.date.today().timetuple()))  # 1612368000 日时间戳, datetime没有给定字符串转换为时间戳的方法还要借助time模块
print('默认生成当日时间戳', ymd_stamp)
stamp = int(time.time())
ymd_str1 = datetime.date.fromtimestamp(stamp)  # 2021-02-04
print('根据时间戳生成时间字符串', ymd_str1)

  

2. 今日零点和某一时间节点比如9:30的字符串和时间戳转换

import datetime
import time


# 今日零点字符串
today_ymd_0001 = time.strftime("%Y-%m-%d")
today_ymd_0002 = datetime.date.today().strftime('%Y-%m-%d')  # 2021-02-04
today_ymd_0003 = datetime.datetime.now().replace(hour=0, minute=0, second=0, microsecond=0).strftime("%Y-%m-%d")  # 有year/month/day/hour/minute/second/microsecond 7个参数v
print('今日0:00时间字符串: ', today_ymd_0001, today_ymd_0002, today_ymd_0003)
# 今日0:00时间字符串:  2021-02-04 2021-02-04 2021-02-04

# 今日零点时间戳
today_000 = int(datetime.datetime.now().replace(hour=0, minute=0, second=0, microsecond=0).timestamp())
print('今日0:00时间戳: ', today_000)

# 今日9:30的时间字符串
time_930_str = datetime.datetime.now().replace(hour=9, minute=30, second=0, microsecond=0).strftime("%Y-%m-%d %H:%M:%S")
print('今日9:30时间字符串: ', time_930_str, type(time_930_str))

# 今日9:30的时间戳
today_930 = int(datetime.datetime.now().replace(hour=9, minute=30, second=0, microsecond=0).timestamp())
print('今日9:30的时间戳: ', today_930)

# 任意字符串转换为时间戳
ymd_stamp = datetime.datetime.strptime("2015-02-28 14:19:05.512", "%Y-%m-%d %H:%M:%S.%f").timestamp()
print('datetime.datetime字符串转换为时间戳', ymd_stamp)

  

3.计算多少日前日期timedelta

参数可选、默认值都为0:datetime.timedelta(days=0, seconds=0, microseconds=0, milliseconds=0, minutes=0, hours=0, weeks=0)

import time
import datetime

today = datetime.date.today()
before_year = datetime.date.today() - datetime.timedelta(days=365)
before_year_stamp = int(time.mktime(time.strptime(before_year.strftime('%Y-%m-%d'), '%Y-%m-%d')))
print(today, before_year, before_year_stamp)
# 2021-02-04 2020-02-05 1580832000

4. 计算日周月年relativedelta

#!/usr/bin/env python
# -*- encoding: utf-8 -*-
"""
"""

import datetime
import time
from dateutil.relativedelta import relativedelta
# timedelta 实现不了周月年的减法


def get_days_st_et(days):
    """
    获取今天之前的日期
    :param days:
    :return:
    """

    pre_day = datetime.date.today() - datetime.timedelta(days=days)
    pre_day_ts = int(time.mktime(pre_day.timetuple()))
    pre_day_str = pre_day.strftime("%Y-%m-%d")
    return pre_day_str, pre_day_ts


def get_weeks_st_et(weeks):
    """
    获取今天之前的日期
    :param months:
    :return:
    """

    pre_day = datetime.date.today() - relativedelta(weeks=weeks)
    pre_day_ts = int(time.mktime(pre_day.timetuple()))
    pre_day_str = pre_day.strftime("%Y-%m-%d")

    return pre_day_str, pre_day_ts


def get_months_st_et(months):
    """
    获取今天之前的日期
    :param months:
    :return:
    """

    pre_day = datetime.date.today() - relativedelta(months=months)
    pre_day_ts = int(time.mktime(pre_day.timetuple()))
    pre_day_str = pre_day.strftime("%Y-%m-%d")

    return pre_day_str, pre_day_ts


def get_years_st_et(years):
    """
    获取今天之前的日期
    :param years:
    :return:
    """

    pre_day = datetime.date.today() - relativedelta(years=years)
    pre_day_ts = int(time.mktime(pre_day.timetuple()))
    pre_day_str = pre_day.strftime("%Y-%m-%d")

    return pre_day_str, pre_day_ts


if __name__ == '__main__':
    # 今日时间戳
    today_now = datetime.date.today()
    today_timestamp = int(time.mktime(today_now.timetuple()))
    print('今日: {}/{}'.format(today_now, today_timestamp))

    # 最近一周
    pre_ts, pre_str = get_days_st_et(days=2)
    print('最近日: {}/{}'.format(pre_ts, pre_str))

    # 最近一周
    week_ts, week_str = get_weeks_st_et(weeks=1)
    print('最近周: {}/{}'.format(week_ts, week_str))

    # 最近1个月
    month_ts, month_str = get_months_st_et(months=1)
    print('最近月: {}/{}'.format(month_ts, month_str))

    # 最近一年
    year_ts, year_str = get_years_st_et(years=1)
    print('最近年: {}/{}'.format(year_ts, year_str))

  

 

 

 

 

 


 

posted @ 2021-02-04 18:06  Adamanter  阅读(178)  评论(0)    收藏  举报