python字符串到日期时间,找到昨天然后回到字符串

dbJ*_*nes 5 python datetime

我正在尝试执行以下操作:

  1. 从文件中读取日期(日期格式为 %Y-%m-%d)
  2. 将字符串转换为日期时间对象(我正在使用 strptime 执行此操作)
  3. 获取日期时间的一天
  4. 将前一天 (look_back) 转换回给定格式的字符串

步骤 1 和 2 不是问题,我是这样完成的:

import datetime
from datetime import timedelta
import time

now = datetime.datetime.now() #checks current datetime

### READ LAST RUN DATETIME ###
try:
    test = open("last_settings.ini", "r") #opens file in read mode
    print "Name of the file: ", test.name

    last_run = test.read(10); # just reads the date
    print "Program was last run: %s" % last_run
    test.close()
    firstRun = 'False'
except:
    print "Settings file does not exist"
    #test = open("last_settings.ini", "w+") #creates the file
    #test.close()

    #first_run = 'True'
    #look_back = str(now-timedelta(days=14)) #sets initial lookBack date of two weeks
    #print "Pulling down all paid invoices from date " + look_back


### 24 hour lookback ###
look_back = time.strptime(last_run, "%Y-%m-%d")
Run Code Online (Sandbox Code Playgroud)

但是,我尝试获取给定日期之前的日期(上面的#3)的每种方法都会引发错误。我的代码:

look_back = look_back-timedelta(days=1)
Run Code Online (Sandbox Code Playgroud)

错误:

look_back = look_back-timedelta(days=1)
TypeError: unsupported operand type(s) for -: 'time.struct_time' and 'datetime.timedelta'
Run Code Online (Sandbox Code Playgroud)

有关于如何做到这一点的想法?

Mar*_*ers 5

datetime.datetime对象具有一个strptime()方法 ,以及

read_date = datetime.datetime.strptime(last_run, '%Y-%m-%d')
previous_day = read_date - datetime.timedelta(days=1)
formatted_previous_day = previous_day.strftime('%Y-%m-%d')
Run Code Online (Sandbox Code Playgroud)