美文网首页
python常见日期、时间操作

python常见日期、时间操作

作者: 高明无思 | 来源:发表于2021-06-01 19:02 被阅读0次

日期字符串转日期对象,日期对象转时间戳,获取当前时间,获取前一天时间,获取后一天时间等这些在日常项目中大量重复操作不值得反复去写,因此封装为data_helper.py文件,可以直接集成到项目当中使用.
date_helper.py

#!/usr/bin/env python
# coding: utf-8 
# Gao Ming Ming Create At 2021-06-01
# Description:时间日期相关操作的封装
import calendar
import time
from datetime import datetime,timedelta
from dateutil.relativedelta import relativedelta


def get_month_day(year, month):
    '''
        获取某年某月的所有天
    '''
    strMon = '{:0>4}{:0>2}'.format(year, month)
    monrange = calendar.monthrange(year, month)
    days = []
    for i in range(monrange[1]):
        days.append('{:0>4}{:0>2}{:0>2}'.format(year, month, i + 1))
    return days

def get_date_timestamp(date_str):
    '''
        日期字符串转时间戳
        date_str:"2021-06-01" 或者 "2021-06-01 18:20:10"
        return:

    '''
    try:
        if len(date_str) == 10:
            date_str = "{} 00:00:00".format(date_str)

        dt = datetime.strptime(date_str, "%Y-%m-%d")
        return int(time.mktime(dt.timetuple()))
    except Exception as e:
        print("the format of date is wrong,eg:2020-08-01")

def get_days_between_dates(start_date,end_date):
    '''
        获取两天之间的所有日期字符串
        start_date: "2021-06-01" 或者 "2021-06-01 18:20:10"
        end_date : "2021-06-01" 或者 "2021-06-01 18:20:10"
    '''
    try:
        if len(start_date) == 10:
            start_date = "{} 00:00:00".format(start_date)

        if len(end_date) == 10:
            end_date = "{} 00:00:00".format(end_date)

        start = datetime.strptime(start_date, "%Y-%m-%d %H:%M:%S")
        end = datetime.strptime(end_date, "%Y-%m-%d %H:%M:%S")
        days = list()
        while start < end:
            days.append(start.strftime("%Y-%m-%d"))
            start += timedelta(days=1)
        return days
    except Exception as e:
        print(e)

def get_month_between_dates(start_date,end_date):
    '''
        获取两个日期之间的月份字符串集合
        pip install python-dateutil
    '''
    try:
        if len(start_date) == 10:
            start_date = "{} 00:00:00".format(start_date)

        if len(end_date) == 10:
            end_date = "{} 00:00:00".format(end_date)

        start = datetime.strptime(start_date, "%Y-%m-%d %H:%M:%S")
        end = datetime.strptime(end_date, "%Y-%m-%d %H:%M:%S")

        monthes = list()
        while start <= end:
            monthes.append(start.strftime("%Y-%m"))
            start += relativedelta(months=+1)
        return monthes
    except Exception as e:
        print(e)

def convert_timestamp_to_date(time_stamp):
    '''时间戳转日期'''
    try:
        dt = datetime.fromtimestamp(time_stamp)                                                                                                                                                          
        return dt.strftime("%Y-%m-%d %H:%M:%S")
    except Exception as e:
        print(e)

def convert_date_to_timestamp(dt):
    '''
        将日期对象转化为时间戳
    '''
    try:
        return int(time.mktime(dt.timetuple()))
    except Exception as e:
        print(e)

def current():
    '''
        获取当前时间
    '''
    return datetime.now()

def yesterday(dt):
    '''
        获取前一天
    '''
    return dt + datetime.timedelta(days=-1)

def tomorrow(dt):
    '''
       获取后一天
    '''
    return dt + datetime.timedelta(days=1)

相关文章

网友评论

      本文标题:python常见日期、时间操作

      本文链接:https://www.haomeiwen.com/subject/srlgsltx.html