4

I am trying to get a date an year from todays date into a variable. Below is my code.

import time
import datetime
today = time.strftime("%m/%d/%Y")
today_format = datetime.datetime.strptime(today, "%m/%d/%Y")
print (today_format)
exp_date = str(today_format + datetime.timedelta(days=365)).split(" ")
exp = exp_date[0]
print (exp)`

Above code prints:

2017-12-14 00:00:00
2018-12-14

Any idea how to get it to print 12/14/2018??

OneCricketeer
  • 179,855
  • 19
  • 132
  • 245
Sel_Python
  • 191
  • 2
  • 7
  • 16

4 Answers4

8

using dateutil.relativedelta package, you can do:

import datetime
from dateutil.relativedelta import relativedelta

one_year_from_now = datetime.datetime.now() + relativedelta(years=1)
date_formated = one_year_from_now.strftime("%d/%m/%Y")
print date_formated

how to install dateutil package

Moher
  • 741
  • 7
  • 17
4

Try using the datetime module:

datetime.datetime.today().strftime('%m/%d/%Y')

Prints:

'12/14/2017'
Ibraheem Ahmed
  • 11,652
  • 2
  • 48
  • 54
0

If you use pandas

import pandas as pd
pd.to_datetime('now') + pd.offsets.DateOffset(years=1)
Anton vBR
  • 18,287
  • 5
  • 40
  • 46
0

Late to the party for this one, but had the same issue and this is my solution:

date1 = datetime.today().strftime('%Y-%m-%d')
def monthreduct(date):
    
    def under10(date):
        if int(date[1]) < 10:
               date[1] = f'0{date[1]}'
               
    date = date.split('-')    
    date[1] = int(date[1])  
    if date[1] <= 1:
        date[0] = int(date[0]) - 1
        date[0] = str(date[0])
        date[1] = str(12)
    else:
        date[1] = int(date[1]) - 1
    date[1] = str(date[1])
    under10(date)
    return "-".join(date)

This will allow a date, for example 12-09-2030 to be adjusted to 12-08-2030.