首页 > Python资料 博客日记

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

2024-03-17 13:00:05Python资料围观142

Python资料网推荐Python处理日期方法大全、三十种方法这篇文章给大家,欢迎收藏Python资料网享受知识的乐趣

一、使用 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)

版权声明:本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若内容造成侵权/违法违规/事实不符,请联系邮箱:jacktools123@163.com进行投诉反馈,一经查实,立即删除!

标签:

相关文章

本站推荐