Get the date a year from today in dd/mm/yyyy format in python
Question:
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??
Answers:
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
Try using the datetime module:
datetime.datetime.today().strftime('%m/%d/%Y')
Prints:
'12/14/2017'
If you use pandas
import pandas as pd
pd.to_datetime('now') + pd.offsets.DateOffset(years=1)
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.
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??
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
Try using the datetime module:
datetime.datetime.today().strftime('%m/%d/%Y')
Prints:
'12/14/2017'
If you use pandas
import pandas as pd
pd.to_datetime('now') + pd.offsets.DateOffset(years=1)
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.