1

The dates are in format "YYYYMMDD" and I want it in "YYYYMMDD-(1)", i.e previous day.

For example consider date 20080101 the previous date would be 20071231.

Is there any built in function to do this ?

jpp
  • 159,742
  • 34
  • 281
  • 339
  • 3
    Possible duplicate of [How to subtract a day from a date?](https://stackoverflow.com/questions/441147/how-to-subtract-a-day-from-a-date) – jsheeran Apr 20 '18 at 07:23
  • convert string to date, substract a day, convert date to string in your format. Even better: store dates as datetime.date to begin with and do not care about the format unless you print it. Solutions for these part-problems are galore on SO - search them. – Patrick Artner Apr 20 '18 at 07:24
  • 2
    Possible duplicate of [Converting a string to a formatted date-time string using Python](https://stackoverflow.com/questions/2316987/converting-a-string-to-a-formatted-date-time-string-using-python) – Bill F Apr 20 '18 at 07:26

1 Answers1

2

You can perform this transformation in 3 steps:

  1. Convert string to datetime.
  2. Subtract one day.
  3. Convert datetime object to str.

Here is an example:

from datetime import datetime, timedelta

x = '20080101'
f = '%Y%m%d'

res = (datetime.strptime(x, f) - timedelta(days=1)).strftime(f)
# '20071231'
jpp
  • 159,742
  • 34
  • 281
  • 339