ChatGPT解决这个技术问题 Extra ChatGPT

如何从日期中减去一天?

我有一个 Python datetime.datetime 对象。减去一天的最佳方法是什么?

该线程对于将一年中的某一天转换为日期直接有用。

B
Boris Verkhovskiy

您可以使用 timedelta 对象:

from datetime import datetime, timedelta
    
d = datetime.today() - timedelta(days=days_to_subtract)

如果您不忽略时区,那么 the answer is more complex
另外,您如何将其与特定日期联系起来。请参阅我的问题:stackoverflow.com/questions/43092508/…
它也适用于其他单位,例如,我已将它与 timedelta(minutes=12) 一起使用。
文档说这将返回“表示两个日期、时间或日期时间实例之间差异的持续时间......”。您如何获得 5 天前或 5 天后的实际日期?
@jfs我认为这个答案就时区而言很好。如果减去一天,实际上可能会减去 23 或 25 小时,但时间部分将保持不变。这就是我所期望的正常行为。夏令时 (DST) 使得 1 天并不总是 24 小时。
S
S.Lott

减去 datetime.timedelta(days=1)


j
jfs

如果您的 Python 日期时间对象是时区感知的,那么您应该小心避免 DST 转换出现错误(或由于其他原因而更改 UTC 偏移量):

from datetime import datetime, timedelta
from tzlocal import get_localzone # pip install tzlocal

DAY = timedelta(1)
local_tz = get_localzone()   # get local timezone
now = datetime.now(local_tz) # get timezone-aware datetime object
day_ago = local_tz.normalize(now - DAY) # exactly 24 hours ago, time may differ
naive = now.replace(tzinfo=None) - DAY # same time
yesterday = local_tz.localize(naive, is_dst=None) # but elapsed hours may differ

通常,如果本地时区的 UTC 偏移在最后一天发生了变化,day_agoyesterday 可能会有所不同。

例如,夏令时/夏令时在美国/洛杉矶时区的 2014 年 11 月 2 日星期日凌晨 02:00:00 结束,因此如果:

import pytz # pip install pytz

local_tz = pytz.timezone('America/Los_Angeles')
now = local_tz.localize(datetime(2014, 11, 2, 10), is_dst=None)
# 2014-11-02 10:00:00 PST-0800

那么 day_agoyesterday 不同:

day_ago 正好是 24 小时前(相对于现在),但在上午 11 点,而不是现在的上午 10 点

昨天是昨天上午 10 点,但它是 25 小时前(相对于现在),而不是 24 小时。

pendulum module 自动处理它:

>>> import pendulum  # $ pip install pendulum

>>> now = pendulum.create(2014, 11, 2, 10, tz='America/Los_Angeles')
>>> day_ago = now.subtract(hours=24)  # exactly 24 hours ago
>>> yesterday = now.subtract(days=1)  # yesterday at 10 am but it is 25 hours ago

>>> (now - day_ago).in_hours()
24
>>> (now - yesterday).in_hours()
25

>>> now
<Pendulum [2014-11-02T10:00:00-08:00]>
>>> day_ago
<Pendulum [2014-11-01T11:00:00-07:00]>
>>> yesterday
<Pendulum [2014-11-01T10:00:00-07:00]>

S
Sahil kalra

只是为了详细说明一种替代方法和一个有用的用例:

从当前日期时间减去 1 天:

from datetime import datetime, timedelta print datetime.now() + timedelta(days=-1) # 这里我加了一个负的timedelta

在案例中很有用,如果您想从当前日期时间增加 5 天并减去 5 小时。即从现在起 5 天后的日期时间是多少,但少了 5 小时?

from datetime import datetime, timedelta print datetime.now() + timedelta(days=5, hours=-5)

它可以类似地与其他参数一起使用,例如秒、周等


P
PlagTag

当我想计算即上个月的第一天/最后一天或其他相对时间增量等时,我也喜欢使用另一个不错的功能......

dateutil 函数中的 relativedelta 函数(对 datetime 库的强大扩展)

import datetime as dt
from dateutil.relativedelta import relativedelta
#get first and last day of this and last month)
today = dt.date.today()
first_day_this_month = dt.date(day=1, month=today.month, year=today.year)
last_day_last_month = first_day_this_month - relativedelta(days=1)
print (first_day_this_month, last_day_last_month)

>2015-03-01 2015-02-28

g
gr4viton

存在通用箭头模块

import arrow
utc = arrow.utcnow()
utc_yesterday = utc.shift(days=-1)
print(utc, '\n', utc_yesterday)

输出:

2017-04-06T11:17:34.431397+00:00 
 2017-04-05T11:17:34.431397+00:00

V
VISHAKHA AGARWAL
class myDate:

    def __init__(self):
        self.day = 0
        self.month = 0
        self.year = 0
        ## for checking valid days month and year
        while (True):
            d = int(input("Enter The day :- "))
            if (d > 31):
                print("Plz 1 To 30 value Enter ........")
            else:
                self.day = d
                break

        while (True):
            m = int(input("Enter The Month :- "))
            if (m > 13):
                print("Plz 1 To 12 value Enter ........")
            else:
                self.month = m
                break

        while (True):
            y = int(input("Enter The Year :- "))
            if (y > 9999 and y < 0000):
                print("Plz 0000 To 9999 value Enter ........")
            else:
                self.year = y
                break
    ## method for aday ands cnttract days
    def adayDays(self, n):
        ## aday days to date day
        nd = self.day + n
        print(nd)
        ## check days subtract from date
        if nd == 0: ## check if days are 7  subtracted from 7 then,........
            if(self.year % 4 == 0):
                if(self.month == 3):
                    self.day = 29
                    self.month -= 1
                    self.year = self. year
            else:
                if(self.month == 3):
                    self.day = 28
                    self.month -= 1
                    self.year = self. year
            if  (self.month == 5) or (self.month == 7) or (self.month == 8) or (self.month == 10) or (self.month == 12):
                self.day = 30
                self.month -= 1
                self.year = self. year
                   
            elif (self.month == 2) or (self.month == 4) or (self.month == 6) or (self.month == 9) or (self.month == 11):
                self.day = 31
                self.month -= 1
                self.year = self. year

            elif(self.month == 1):
                self.month = 12
                self.year -= 1    
        ## nd == 0 if condition over
        ## after subtract days to day io goes into negative then
        elif nd < 0 :   
            n = abs(n)## return positive if no is negative
            for i in range (n,0,-1): ## 
                
                if self.day == 0:

                    if self.month == 1:
                        self.day = 30
                        
                        self.month = 12
                        self.year -= 1
                    else:
                        self.month -= 1
                        if(self.month == 1) or (self.month == 3)or (self.month == 5) or (self.month == 7) or (self.month == 8) or (self.month == 10) or (self.month ==12):
                            self.day = 30
                        elif(self.month == 4)or (self.month == 6) or (self.month == 9) or (self.month == 11):
                            self.day = 29
                        elif(self.month == 2):
                            if(self.year % 4 == 0):
                                self.day == 28
                            else:
                                self.day == 27
                else:
                    self.day -= 1

        ## enf of elif negative days
        ## adaying days to DATE
        else:
            cnt = 0
            while (True):

                if self.month == 2:  # check leap year
                    
                    if(self.year % 4 == 0):
                        if(nd > 29):
                            cnt = nd - 29
                            nd = cnt
                            self.month += 1
                        else:
                            self.day = nd
                            break
                ## if not leap year then
                    else:  
                    
                        if(nd > 28):
                            cnt = nd - 28
                            nd = cnt
                            self.month += 1
                        else:
                            self.day = nd
                            break
                ## checking month other than february month
                elif(self.month == 1) or (self.month == 3) or (self.month == 5) or (self.month == 7) or (self.month == 8) or (self.month == 10) or (self.month == 12):
                    if(nd > 31):
                        cnt = nd - 31
                        nd = cnt

                        if(self.month == 12):
                            self.month = 1
                            self.year += 1
                        else:
                            self.month += 1
                    else:
                        self.day = nd
                        break

                elif(self.month == 4) or (self.month == 6) or (self.month == 9) or (self.month == 11):
                    if(nd > 30):
                        cnt = nd - 30
                        nd = cnt
                        self.month += 1

                    else:
                        self.day = nd
                        break
                ## end of month condition
        ## end of while loop
    ## end of else condition for adaying days
    def formatDate(self,frmt):

        if(frmt == 1):
            ff=str(self.day)+"-"+str(self.month)+"-"+str(self.year)
        elif(frmt == 2):
            ff=str(self.month)+"-"+str(self.day)+"-"+str(self.year)
        elif(frmt == 3):
            ff =str(self.year),"-",str(self.month),"-",str(self.day)
        elif(frmt == 0):
            print("Thanky You.....................")
            
        else:
            print("Enter Correct Choice.......")
        print(ff)
            
            

dt = myDate()
nday = int(input("Enter No. For Aday or SUBTRACT Days :: "))
dt.adayDays(nday)
print("1 : day-month-year")
print("2 : month-day-year")
print("3 : year-month-day")
print("0 : EXIT")
frmt = int (input("Enter Your Choice :: "))
dt.formatDate(frmt)

    enter code here

尽可能使用标准库更好,因为它通常由很多人维护,错误少且执行速度更快