首页 > 编程语言 >Python处理日期方法大全、三十种方法

Python处理日期方法大全、三十种方法

时间:2023-11-08 16:56:57浏览次数:39  
标签:三十种 Python datetime date print import now 方法 today

一、使用 time 模块展示当前日期和时间

import time
from time import gmtime, strftime
 
t = time.localtime()  
print (time.asctime(t))  # Sun May 7 09:30:37 2017
print(strftime("%a, %d %b %Y %H:%M:%S +0000", gmtime()))  # Sun, 07 May 2017 04:00:37 +0000
print(strftime("%A", gmtime()))  # Sunday
print(strftime("%D", gmtime()))  # 05/07/17
print(strftime("%B", gmtime()))  # May
print(strftime("%y", gmtime()))  # 17
 
# Convert seconds into GMT date
print(strftime("%a, %d %b %Y %H:%M:%S +0000", gmtime(1234567890)))  # Fri, 13 Feb 2009 23:31:30 +0000

二、将天、小时、分钟转换为秒

SECONDS_PER_MINUTE = 60
SECONDS_PER_HOUR = 3600
SECONDS_PER_DAY = 86400
 
# 输入天、小时、分钟、秒的数量
days = int(input("Enter number of Days: "))
hours = int(input("Enter number of Hours: "))
minutes = int(input("Enter number of Minutes: "))
seconds = int(input("Enter number of Seconds: "))
 
# 计算
total_seconds = days * SECONDS_PER_DAY
total_seconds = total_seconds + ( hours * SECONDS_PER_HOUR)
total_seconds = total_seconds + ( minutes * SECONDS_PER_MINUTE)
total_seconds = total_seconds + seconds
 
# 结果
print("Total number of seconds: ","%d"%(total_seconds))
'''
Enter number of Days: 5
Enter number of Hours: 36
Enter number of Minutes: 24
Enter number of Seconds: 15
Total number of seconds: 563055
'''

三、使用 Pandas 获取当前日期和时间

import pandas as pd
print(pd.datetime.now())  # 2018-01-19 16:08:28.393553
print(pd.datetime.now().date())  # 2018-01-19
print(pd.datetime.now().year)  # 2018
print(pd.datetime.now().month)  # 1
print(pd.datetime.now().day)  # 19
print(pd.datetime.now().hour)  # 16
print(pd.datetime.now().minute)  # 8
print(pd.datetime.now().second)  # 28
print(pd.datetime.now().microsecond)  # 394553

四、将字符串转换为日期时间对象

from datetime import datetime
from dateutil import parser

d1 = "Jan 7 2015  1:15PM"
d2 = "2015 Jan 7  1:33PM"

# If you know date format
date1 = datetime.strptime(d1, '%b %d %Y %I:%M%p')
print(type(date1))  # class 'datetime.datetime'
print(date1)  # 2015-01-07 13:15:00

# If you don't know date format
date2 = parser.parse(d2)
print(type(date2))  # class 'datetime.datetime'
print(date2)  # 2015-01-07 13:33:00

五、以毫秒为单位获取当前时间

import time
 
milliseconds = int(round(time.time() * 1000))
print(milliseconds)  # 1516364270650

六、以 MST、EST、UTC、GMT 和 HST 获取当前日期时间

from datetime import datetime
from pytz import timezone
 
mst = timezone('MST')
print("Time in MST:", datetime.now(mst))  # Time in MST: 2017-01-19 06:06:14.495605-07:00
est = timezone('EST')
print("Time in EST:", datetime.now(est))  # Time in EST: 2017-01-19 08:06:14.496606-05:00
utc = timezone('UTC')
print("Time in UTC:", datetime.now(utc))  # Time in UTC: 2017-01-19 13:06:14.496606+00:00
gmt = timezone('GMT')
print("Time in GMT:", datetime.now(gmt))  # Time in GMT: 2017-01-19 13:06:14.496606+00:00
hst = timezone('HST')
print("Time in HST:", datetime.now(hst))  # Time in HST: 2017-01-19 03:06:14.497606-10:00

七、从给定的日期当中获取星期几

import datetime
 
dayofweek = datetime.date(2010, 6, 16).strftime("%A")
print(dayofweek)  # Wednesday

# weekday()方法: 0代表周一,6代表周日
print("weekday():", datetime.date(2010, 6, 16).weekday())  # weekday(): 2
 
# isoweekday() 方法: 1代表周一,7代表周日
print("isoweekday()", datetime.date(2010, 6, 16).isoweekday())  # isoweekday() 3
 
dayofweek = datetime.datetime.today().strftime("%A")
print(dayofweek)  # Friday
print("weekday():", datetime.datetime.today().weekday())  # weekday(): 4
print("isoweekday()", datetime.datetime.today().isoweekday())  # isoweekday(): 5

八、计算两个日期时间对象之间的时差

import datetime
from datetime import timedelta
 
datetimeFormat = '%Y-%m-%d %H:%M:%S.%f'
date1 = '2016-04-16 10:01:28.585'
date2 = '2016-03-10 09:56:28.067'
diff = datetime.datetime.strptime(date1, datetimeFormat)\
    - datetime.datetime.strptime(date2, datetimeFormat)
 
print("Difference:", diff)  # Difference: 37 days, 0:05:00.518000
print("Days:", diff.days)  # Days: 37
print("Microseconds:", diff.microseconds)  # Microseconds: 518000
print("Seconds:", diff.seconds)  # Seconds: 300

九、将 5 分钟添加到 Unix 时间戳

import datetime
import calendar
 
future = datetime.datetime.utcnow() + datetime.timedelta(minutes=5)
print(calendar.timegm(future.timetuple()))  # 1621069619

十、遍历一系列日期

import datetime

start = datetime.datetime.strptime("21-06-2020", "%d-%m-%Y")
end = datetime.datetime.strptime("05-07-2020", "%d-%m-%Y")
date_generated = [start + datetime.timedelta(days=x) for x in range(0, (end - start).days)]

for date in date_generated:
    print(date.strftime("%d-%m-%Y"))

十一、巴黎时间更改为纽约时间

import pendulum
 
in_paris = pendulum.datetime(2016, 8, 7, 22, 24, 30, tz='Europe/Paris')
print(in_paris)  # 2016-08-07T22:24:30+02:00
 
in_us = in_paris.in_timezone('America/New_York')
print(in_us)  # 2016-08-07T16:24:30-04:00

十二、使用 Python 获得最后7个工作日

from datetime import date
from datetime import timedelta
 
today = date.today()
 
for i in range(7):
    d = today - timedelta(days=i)
    if d.weekday() < 5:
        print(d)

十三、从今天的日期和一个人的生日推算年龄

from datetime import date
 
 
def calculate_age(born):
    today = date.today()
    try:
        birthday = born.replace(year=today.year)
    except ValueError:
        birthday = born.replace(year=today.year, month=born.month + 1, day=1)
    if birthday > today:
        return today.year - born.year - 1
    else:
        return today.year - born.year
 
 
print(calculate_age(date(2001, 3, 1)))

十四、获得本月的第一个星期二

import calendar
from datetime import datetime
 
c = calendar.Calendar(firstweekday=calendar.SUNDAY)
monthcal = c.monthdatescalendar(datetime.today().year, datetime.today().month)
#Python小白学习交流群:153708845  
try:
    tues = [day for week in monthcal for day in week if
            day.weekday() == calendar.TUESDAY and day.month == datetime.today().month][0]
    print(tues)
except IndexError:
    print('No date found')

十五、将整数转换为日期对象

from datetime import datetime

i = 1545730073
timestamp = datetime.fromtimestamp(i)

print(timestamp)  # 2018-12-25 14:57:53
print(type(timestamp))

十六、当前日期减去 N 天的天数

from datetime import datetime, timedelta

d = datetime.today() - timedelta(days=5)
print(d)

十七、比较两个日期

import datetime

a = datetime.datetime(2020, 12, 31, 23, 59, 59)
b = datetime.datetime(2020, 11, 30, 23, 59, 59)

print(a < b)
print(a > b)

十八、从 datetime 对象中提取年份

import datetime
 
year = datetime.date.today().year
print(year)

十九、根据日期找到星期几

import pendulum
 
dt = pendulum.parse('2021-05-18')
print(dt.day_of_week)  # 2
 
dt = pendulum.parse('2021-05-01')
print(dt.day_of_week) # 6
 
dt = pendulum.parse('2021-05-21')
print(dt.day_of_week) # 5

二十、从当前日期获取 7 天前的日期

from datetime import datetime, timedelta
 
now = datetime.now()
 
for x in range(7):
    d = now - timedelta(days=x)
    print(d.strftime("%Y-%m-%d"))

二十一、将两个日期时间对象之间的差值转换为秒

import datetime
 
time1 = datetime.datetime.strptime('19 01 2021', '%d %m %Y')
time2 = datetime.datetime.strptime('25 01 2021', '%d %m %Y')
 
difference = time2 - time1
print(difference)  # 6 days, 0:00:00
 
seconds = difference.total_seconds()
print(seconds)  # 518400.0

二十二、获得任何一个月的第N个星期五

import calendar

# 取2021年5月的第三个星期五
c = calendar.Calendar(firstweekday=calendar.SUNDAY)
year = 2021
month = 5
n = 2  # 取第三个
monthcal = c.monthdatescalendar(year, month)
 
try:
    third_friday = [
        day for week in monthcal 
            for day in week if
                day.weekday() == calendar.FRIDAY and day.month == month
    ][n]
    print(third_friday)  # 2021-05-21
except IndexError:
    print('No date found')

二十三、根据周数获取日期

import datetime
from dateutil.relativedelta import relativedelta
 
week = 25
year = 2021
date = datetime.date(year, 1, 1) + relativedelta(weeks=+week)
print(date)  # 2021-06-25

二十四、获取特定日期的工作日

import datetime
 
print(datetime.date(2020, 5, 15).isocalendar()[2])  # 5

二十五、创建一个 15 分钟前的 DateTime

import datetime
#Python小白学习交流群:153708845  
dt = datetime.datetime.now() - datetime.timedelta(minutes=15)
print(dt)  # 2021-05-15 22:25:55.897365

二十六、从特定日期获取周的开始和结束日期

import pendulum
 
dt = pendulum.datetime(2012, 9, 5)
 
start = dt.start_of('week')
print(start.to_datetime_string())  # 2012-09-03 00:00:00
 
end = dt.end_of('week')
print(end.to_datetime_string())  # 2012-09-09 23:59:59

二十七、两个日期之间的差异(以秒为单位)

from datetime import datetime
#Python小白学习交流群:153708845 
fmt = '%Y-%m-%d %H:%M:%S'
d1 = datetime.strptime('2020-01-01 17:31:22', fmt)
d2 = datetime.strptime('2020-01-03 17:31:22', fmt)
 
days_diff = d2 - d1
print(days_diff.days * 24 * 60 * 60)  # 172800

二十八、以这种格式获取昨天的日期MMDDYY

from datetime import date, timedelta
 
yesterday = date.today() - timedelta(days=1)
print(yesterday.strftime('%m%d%y'))  # 051421

二十九、根据今天的日期获取上周三的日期

from datetime import date
from datetime import timedelta

today = date.today()

offset = (today.weekday() - 2) % 7
wednesday = today - timedelta(days=offset)
print(wednesday)  # 2021-05-12

三十、所有可用时区的列表打印

import pytz

for i in pytz.all_timezones:
    print(i)

标签:三十种,Python,datetime,date,print,import,now,方法,today
From: https://www.cnblogs.com/xxpythonxx/p/17817779.html

相关文章

  • python 图书借阅系统
    importtkinterastkfromtkinterimportmessageboxclassApplication(tk.Frame):def__init__(self,library,master=None):super().__init__(master)self.library=libraryself.grid()self.create_widgets()defcrea......
  • Java数组中常见的方法
    一、前言代码://给定一个数组int[]arr={234,312,32,1321,321,43};int[]arr1=newint[6];int[]arr2={1,3,7,8,32,432,432};二、复制1、arraycopy完成数组的复制//复制arr源数组,srcPos(0)源数组中起点的位置,arr1目标数组,des......
  • 常用python自动化脚本
    目录自动化文件管理使用Python进行网页抓取文本处理和操作自动发送电子邮件自动化Excel电子表格与数据库交互自动化系统任务网络自动化数据清理和转换自动化PDF操作1.自动化文件管理1.1-排序目录中的文件# Python脚本,用于根据文件扩展名对目录中的文件进行排序i......
  • python初学者学习笔记-第七章-面向对象
    chapter7/面向对象7.1面向对象基础7.1.1定义类:同一类的属性和方法的集合;对象:类的实例化就是对象;7.1.2特征类的三大特性:封装,继承,和多态;封装封装就是将属性和方法相捆绑,形成一个整体;封装可以提高程序的简洁性和安全性;使用者只需调用程序的相关接口,不必关注程序的实现......
  • Java中一些常用的方法实现(更新中)
    一、数组1、indexOfinttargetIndex=indexOf(arr,targetValue);publicstaticintindexOf(int[]arr,inttargetValue){intindex=-1;for(inti=0;i<arr.length;i++){if(arr[i]==targetValue){index=i......
  • python实现STL模型文件体积表面积计算
    没有什么特殊的算法,直接用包,开箱即用fromstlimportmeshimportnumpyasnp#读取stl文件filename='./text.stl'mesh_data=mesh.Mesh.from_file(filename)xyz=(mesh_data.max_-mesh_data.min_)sizel=round(xyz[0]/10,2)sizew=round(xyz[1]/10,2)s......
  • python初学者学习笔记-第八章-模块和包
    chapter8/模块和包8.1.模块8.1.1模块简介类、函数、变量等,都可重复使用。为了方便调用,我们通常把他们放到Python文件之中。单个文件的代码阅读和调用都比较混乱。代码最好分开存储,相似功能的代码放在一起。模块可以帮助我们实现这样的功能。后缀为py的文件都是python的......
  • python ElementTree操作xml节点
    pythonElementTree操作xml节点,包括增删改查xml原文<Voucher><Id>967a198783d14835860574c697478156</Id><Remark>main摘要443344245567583384475</Remark><Delete>需要删除的节点1</Delete><DetailList><Det......
  • 线上问题排查常用分析方法
    线上问题排查方案汇总一、抓包排查接口请求与响应1.针对Linux原生环境的服务,常用的网络协议有udp、tcp、http、dns、ip、port、ssl等,针对Http请求接口,可抓取从源Ip到目的Ip的数据包或者抓取从源Port到指定Port的数据包。常用命令汇总:抓取整包(当前服务器上的调用情况)tcpdump......
  • 简单实现Python采集B站视频
    我们今天要学习的是如何利用Python的requests库编写一个采集B站的小爬虫,都是一些很基础的内容,简单易学,没有什么太过复杂的东西,一起来看看吧。首先安装库:```bashpipinstallrequests```然后,我们可以开始编写爬虫程序:```pythonimportrequestsproxy_host='www.duoip.cn'proxy_......