-1

I have an variable integer that is in the format YYYYMMDD.

How do i convert that variable to datetime while maintaining the format of YYYYMMDD?

date = 20200930

nextday = date + 1

How do i fix this, so the nextday variable displays as 20201001

  • So what's wrong? It's easier to get advice and answers by showing in the program source what you want to do in that format and what you couldn't do (the problem you encountered). – kunif Nov 06 '20 at 22:47
  • Can you please give more details about your use case? You can work with datetime objects and print them/save them in the format you're giving. –  Nov 06 '20 at 22:49
  • See https://stackoverflow.com/a/60273382/7023590 – MarianD Nov 06 '20 at 22:51

1 Answers1

1

If I'm understanding what you need to do correctly, you can easily do it using the datetime package.

First, convert your variable to a date:

import datetime
date = 20200930
dt = datetime.datetime.strptime(str(date), '%Y%m%d')

Now, when you print this, you will see: datetime.datetime(2020, 9, 30, 0, 0).

You can then add a day to it:

dt_new = dt + datetime.timedelta(1)

And specify the format you want to see the new date variable in:

print ('{date: %Y%m%d}'.format(date=dt_new))

which will give: 20201001.