Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python string to datetime, find yesterday then back to string

I am trying to do the following:

  1. read a date from a file (the format of the date is %Y-%m-%d)
  2. convert a string into a datetime obj (i'm doing this with strptime)
  3. get the day prior to the datetime
  4. convert the day prior (look_back) back into a string with a given format

Steps 1 & 2 are not an issue, which I accomplish like so:

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")

However, every method I've tried for getting the date prior to the give date (#3 above) throws an error. My code:

look_back = look_back-timedelta(days=1)

The error:

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

Have ideas about how to do this?

like image 844
dbJones Avatar asked Sep 17 '13 18:09

dbJones


People also ask

How do I get the yesterday timestamp in Python?

Use datetime. date. today() to get today's date in local time. Use today - datetime. timedelta(days=1) to subtract one day from the previous result today .

How does Python calculate yesterday?

You just have to subtract no. of days using 'timedelta' that you want to get back in order to get the date from the past. For example, on subtracting two we will get the date of the day before yesterday.

How do I convert a datetime to a string in Python?

To convert Python datetime to string, use the strftime() function. The strftime() method is a built-in Python method that returns the string representing date and time using date, time, or datetime object.


1 Answers

datetime.datetime objects have a strptime() method as well:

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')
like image 160
Martijn Pieters Avatar answered Oct 05 '22 23:10

Martijn Pieters