python日期操作类

2023-05-16


# -*- coding: utf-8 -*-

'''获取当前日期前后N天或N月的日期'''

from time import strftime, localtime
from datetime import timedelta, date
import calendar

year = strftime("%Y",localtime())
mon  = strftime("%m",localtime())
day  = strftime("%d",localtime())
hour = strftime("%H",localtime())
min  = strftime("%M",localtime())
sec  = strftime("%S",localtime())

def today():
    '''''
    get today,date format="YYYY-MM-DD"
    '''''
    return date.today()

def todaystr():
    '''
    get date string, date format="YYYYMMDD"
    '''
    return year+mon+day

def datetime():
    '''''
    get datetime,format="YYYY-MM-DD HH:MM:SS"
    '''
    return strftime("%Y-%m-%d %H:%M:%S",localtime())

def datetimestr():
    '''''
    get datetime string
    date format="YYYYMMDDHHMMSS"
    '''
    return year+mon+day+hour+min+sec

def get_day_of_day(n=0):
    '''''
    if n>=0,date is larger than today
    if n<0,date is less than today
    date format = "YYYY-MM-DD"
    '''
    if(n<0):
        n = abs(n)
        return date.today()-timedelta(days=n)
    else:
        return date.today()+timedelta(days=n)

def get_days_of_month(year,mon): 
    ''''' 
    get days of month 
    ''' 
    return calendar.monthrange(year, mon)[1] 
  
def get_firstday_of_month(year,mon): 
    ''''' 
    get the first day of month 
    date format = "YYYY-MM-DD" 
    ''' 
    days="01" 
    if(int(mon)<10): 
        mon = "0"+str(int(mon)) 
    arr = (year,mon,days) 
    return "-".join("%s" %i for i in arr) 
  
def get_lastday_of_month(year,mon): 
    ''''' 
    get the last day of month 
    date format = "YYYY-MM-DD" 
    ''' 
    days=calendar.monthrange(year, mon)[1] 
    mon = addzero(mon) 
    arr = (year,mon,days) 
    return "-".join("%s" %i for i in arr) 
  
def get_firstday_month(n=0): 
    ''''' 
    get the first day of month from today 
    n is how many months 
    ''' 
    (y,m,d) = getyearandmonth(n) 
    d = "01" 
    arr = (y,m,d) 
    return "-".join("%s" %i for i in arr) 
  
def get_lastday_month(n=0): 
    ''''' 
    get the last day of month from today 
    n is how many months 
    ''' 
    return "-".join("%s" %i for i in getyearandmonth(n)) 
 
def getyearandmonth(n=0): 
    ''''' 
    get the year,month,days from today 
    befor or after n months 
    ''' 
    thisyear = int(year) 
    thismon = int(mon) 
    totalmon = thismon+n 
    if(n>=0): 
        if(totalmon<=12): 
            days = str(get_days_of_month(thisyear,totalmon)) 
            totalmon = addzero(totalmon) 
            return (year,totalmon,days) 
        else: 
            i = totalmon/12 
            j = totalmon%12 
            if(j==0): 
                i-=1 
                j=12 
            thisyear += i 
            days = str(get_days_of_month(thisyear,j)) 
            j = addzero(j) 
            return (str(thisyear),str(j),days) 
    else: 
        if((totalmon>0) and (totalmon<12)): 
            days = str(get_days_of_month(thisyear,totalmon)) 
            totalmon = addzero(totalmon) 
            return (year,totalmon,days) 
        else: 
            i = totalmon/12 
            j = totalmon%12 
            if(j==0): 
                i-=1 
                j=12 
            thisyear +=i 
            days = str(get_days_of_month(thisyear,j)) 
            j = addzero(j) 
            return (str(thisyear),str(j),days) 
  
def addzero(n): 
    ''''' 
    add 0 before 0-9 
    return 01-09 
    ''' 
    nabs = abs(int(n)) 
    if(nabs<10): 
        return "0"+str(nabs) 
    else: 
        return nabs 

def get_today_month(n=0): 
    ''''' 
    获取当前日期前后N月的日期
    if n>0, 获取当前日期前N月的日期
    if n<0, 获取当前日期后N月的日期
    date format = "YYYY-MM-DD" 
    ''' 
    (y,m,d) = getyearandmonth(n) 
    arr=(y,m,d) 
    if(int(day)<int(d)): 
        arr = (y,m,day) 
    return "-".join("%s" %i for i in arr) 
  

if __name__=="__main__":
    print today()  
    print todaystr()
    print datetime()
    print datetimestr()
    print get_day_of_day(20)
    print get_day_of_day(-3)
    print get_today_month(-3)
    print get_today_month(3)  
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

python日期操作类 的相关文章

  • 使用 pip 或 conda 来管理包? [复制]

    这个问题在这里已经有答案了 我已经使用 matlab 进行机器学习很长一段时间了 最 近切换到 python 并使用其包管理器 pip 安装某些包并成功安装了许多包 几天前 我开始使用 conda 我以前安装的所有软件包都被覆盖 我真的很想
  • 使用列中的日期范围扩展 pandas 数据框

    我有一个 pandas 数据框 其日期和字符串与此类似 Start End Note Item 2016 10 22 2016 11 05 Z A 2017 02 11 2017 02 25 W B 我需要将其扩展 转换为以下内容 在之间填
  • 使用组合时如何解决循环依赖?

    我遇到了如下所示的情况 其中每个类都需要另一个类 并且它创建了循环依赖关系 我在使用 ctypes 包装一些 C 代码时遇到了这种情况 已经有很多关于这个主题的帖子 但我发现它们没有帮助 我需要一些例子 Module A from B im
  • 每当我尝试在 VPS 上使用 Discord 机器人登录时,都会收到“SSL:Certificate_verify_failed”

    我正在将我的机器人从旧的 坏掉的笔记本电脑转移到合适的 VPS 我使用的是较旧的异步版本的 Discord py 0 16 0 因为我在重写之前很长时间就开始研究这个东西了 而且我对 Linux 没有太多经验 因此迁移到 Windows S
  • 使用 python 将 bibtex 文件转换为 html (也许是 pybtex?)

    您好 我想解析 bibtex 出版物文件并对特定字段 例如年份 进行排序并过滤某些内容 然后将其放在网站上 我遇到了 pybtex 它可以读取和解析 bibtex 文件 但它基本上没有记录 我不知道如何对条目进行排序 pybtex 是可行的
  • AttributeError:模块“tensorflow.python.summary.summary”没有属性“FileWriter”

    我收到此错误 尽管我到处都看过file writer tf summary FileWriter path to logs sess graph 被提到为正确的实施this https github com tensorflow tenso
  • 回归模型 statsmodel python

    这更多是一个统计问题 因为代码运行良好 但我正在学习 python 中的回归建模 我在下面使用 statsmodel 编写了一些代码来创建一个简单的线性回归模型 import statsmodels api as sm import num
  • Redis 队列工作程序在 utcparse 中崩溃

    我正在尝试按照以下教程获得基本的 rq 工作 https blog miguelgrinberg com post the flask mega tutorial part xxii background jobs https blog m
  • Jupyter Notebook 找不到 IQSharp

    我一直在尝试为 Quantum Katas 运行 Q 但在找到 Q 内核方面遇到了一些困难 唯一显示的内核是用于 Jupyter Notebook 的 Python 3 内核 奇怪的是 当我执行 jupyter kernalspec lis
  • PyQt5 - 无法使用 QVideoWidget 播放视频

    from PyQt5 QtWidgets import from PyQt5 QtMultimedia import from PyQt5 QtMultimediaWidgets import from PyQt5 QtCore impor
  • pandas dataframe 对列进行排序会引发索引上的 keyerror

    我有以下数据框 df peaklatency snr 0 52 99 0 0 1 54 15 62 000000 2 54 12 82 000000 3 54 64 52 000000 4 54 57 42 000000 5 54 13 7
  • 创建 Pyomo 约束的性能

    我正在用 pyomo 设置一个更大的能量优化问题 正如其他中提到的 设置花费了不合理的时间问题 https stackoverflow com questions 43413067 performance of pyomo to gener
  • 使用 selenium 和 firefox 保存图像

    我正在尝试使用 selenium 服务器和 python 客户端从网站保存图像 我知道图像的 URL 但我无法找到保存它的代码 无论是当它是文档本身还是当它嵌入到当前浏览器会话中时 到目前为止我找到的解决方法是保存页面的屏幕截图 有两种硒方
  • CTRL-C 在 Python 中的行为有所不同

    I ve recently started learning Python long time Java programmer here and currently in the process of writing some simple
  • python中的unicode错误[关闭]

    很难说出这里问的是什么 这个问题是含糊的 模糊的 不完整的 过于宽泛的或修辞性的 无法以目前的形式得到合理的回答 如需帮助澄清此问题以便重新打开 访问帮助中心 help reopen questions 在下面的代码中我收到错误mailSe
  • 如何让 IPython 按类别组织制表符补全的可能性?

    当一个对象有数百个方法时 制表符补全很难使用 通常 有趣的方法是由被检查对象的类而不是其基类定义或重写的方法 如何让 IPython 对其制表符完成可能性进行分组 以便首先检查对象的类中定义的方法和属性 然后是基类中的方法和属性 看起来像是
  • 将 scipy 稀疏矩阵的几行采样到另一个中

    如何对 scipy 稀疏矩阵的某些行进行采样 并从这些采样的行中形成一个新的 scipy 稀疏矩阵 例如 如果我有一个 10 行的 scipy 稀疏矩阵 A 并且我想创建一个新的 scipy 稀疏矩阵 B 其中 A 的第 1 3 4 行 该
  • 如何使用Python3.4在tornado中进行异步mysql操作?

    我现在使用Python3 4 我想在Tornado中使用异步mysql客户端 我已经发现torndb https github com bdarnell torndb但在阅读其源代码后 我认为它无法进行异步mysql操作 因为它只是封装了M
  • python webdriver_manager chrome 自定义配置文件

    如何使 webdriver manager chrome 使用自定义 chrome 用户配置文件 我知道对于 selenium webdriver 我可以这样指定 options Options options add argument f
  • Django中的自动递增值

    我在 django 中有一个表并尝试自动递增它的序列号 在自定义模板中 for 循环用于变量 自定义模板 for i in getodeskview tr td 1 td td i odesk id td td i hours td td

随机推荐

  • devops-2-prometheus

    监控对比 prometheus官方英文文档 入门教程prometheus操作指南 prometheus书学习文档 博客园prometheus系列文章 Prometheus云原生监控pdf 配套视频 服务发现 grafana告警等官方英文文档
  • 443https-公网证书nginx-freessl

    keymanage 生成证书 教程文档 freessl freessl cn acme sh帮助文档 主机记录 acme challenge 记录类型 CNAME 记录值 i7tdkyba41nr7ryod9hr dcv2 httpsaut
  • go基础语法

    基础语法 参考 log 日志 配置基础库参考 zap 日志 zap配置参考 go get u go uber org zap gin 日志 zap 生成 traceid gorm 空指针报错 传递指针地址 结果传递了值报错 reflect
  • 构建监控系统-2-zabbix开发

    参考 zabbix6官网自动发现 zabbix官网 agent监控项说明 go请求zabbix封装参考 ant design pro 前端构建 gin 官方文档 zabbix6 0接口官方文档 zabbix 各表开发介绍 zabbix we
  • 读取文件报错'utf-8' codec can't decode byte 0xb2 in position 49: invalid start byte

    python open打开文件报错 utf 8 codec can t decode byte 0xb2 in position 49 invalid start byte 解决方法 xff1a 1 操作字符为xb2 2 手动查看csv文件
  • python 技术大杂烩

    20230204 python升级报错 pip3 install span class token operator span U pip Could span class token keyword not span fetch URL
  • python 页面点击事件实现selenium

    pip install selenium coding 61 utf 8 from selenium import webdriver driver 61 webdriver Chrome driver maximize window dr
  • python 2.7 连接mysql

    sudo pip install MySQL python import xlrd import MySQLdb cursors conn 61 MySQLdb connect host 61 39 ip 39 user 61 39 use
  • 搭建react antd

    npm install g antd npm WARN antd 64 3 10 8 requires a peer of react 64 gt 61 16 0 0 but none is installed You must insta
  • UCF101和HMDB51数据集的处理 for Human Action Recognition

    数据集简介 xff1a 一 数据集获取 xff1a 1 UCF 101 http crcv ucf edu data UCF101 UCF101 rar 此外 xff0c 该数据集由于超过4G了无法上传百度云 xff0c 所以还在自己移动硬
  • 各种rtos(实时操作系统)比较

    RTOS在国内主要有vxworks和pSOS 现在还有nuclear QNX WinCE 说起好坏吗 其实 vxWorks要好一些 可能 不知道以前国内研究所一直用的VRTX是不是都被vxworks所替代了呢 据说因为VRTX是最早商业化的
  • 使用docker开启和停止一个容器

    我在网上看教程的时候 xff0c 使用docker开启一个容器用的是run命令 xff0c 这里有一个小坑 比如我用run开启了一个mysql xff0c 然后下次还用run开启的话 xff0c 实际上会生成两个mysql容器 正确的做法是
  • 使用python求一次函数和三角函数的交点并画图

    由于一些物理计算的需要 xff0c 我要用电脑将一个一次函数和一个三角函数 xff08 cotan xff09 的图像和交点画出来 本例程使用到的库 xff1a numpy 强大的科学计算库 matlibplot python绘图库 ran
  • 将MyEclipse的配色方案还原到最初的状态(主题还原)

    我的MyEclipse中导入了主题 xff0c 但是现在不想用那种花花绿绿的配色了 xff08 眼睛有点累 xff09 但是想还原却比较麻烦 xff0c 目前有三种方法吧 xff1a 1 xff1a 更换workspace 这种方法需要你重
  • 自己写的一个数组与list转化工具,请大神指正问题

    话不多说上代码 public class ListUtil public static void main String args List lt Integer gt lst1 61 new ArrayList lt Integer gt
  • Python学习记录-----批量发送post请求

    昨天学了一天的Python xff08 我的生产语言是java xff0c 也可以写一些shell脚本 xff0c 算有一点点基础 xff09 xff0c 今天有一个应用场景 xff0c 就正好练手了 这个功能之前再java里写过 xff0
  • 找不到系统安全日志/var/log/secure文件的问题

    今天打算配置一个服务器防止暴力破解的脚本 xff0c 原理不复杂 xff0c 搜索登录错误超过一定次数的ip地址 xff0c 加入防火墙 xff0c 但是在找登录日志的时候出现了问题 一般服务器的ssh登录等操作日志都是 var log s
  • osx多用户设置共享文件夹(MacBook)

    mac平台有很方便的多用户系统 xff08 Unix你懂的 xff09 我本人就一直在使用两个账户 xff0c 各有分工 xff0c 权限不同 有时候我们在一个账户下下载或者使用的文件 xff0c 也需要在另一个账户上使用 xff0c 这就
  • MySQL DROP TABLE操作以及 DROP 大表时的注意事项

    语法 xff1a 删表 sql view plain copy DROP TABLE Syntax DROP TEMPORARY TABLE IF EXISTS tbl name tbl name RESTRICT CASCADE 可一次删
  • python日期操作类

    coding utf 8 39 39 39 获取当前日期前后N天或N月的日期 39 39 39 from time import strftime localtime from datetime import timedelta date