Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to subtract days from current date and return date object in pandas

Tags:

pandas

I want to subtract 30 days from current date and get date in following format.

  final_date = 2019-12-24

I am doing following thing in pandas, but getting timestamp object in return

  final_date = pd.to_datetime(pd.datetime.now().date() - timedelta(30))

How can I do it in pandas?

like image 497
Neil Avatar asked Dec 18 '25 21:12

Neil


2 Answers

There is more solution for subtract today by Timestamp.floor with timedeltas or offsets:

final_date =  pd.Timestamp.now().floor('d') - pd.Timedelta(30, unit='d')
final_date =  pd.to_datetime('now').floor('d') - pd.DateOffset(days=30)
final_date =  pd.to_datetime('now').floor('d') - pd.offsets.Day(30)

print (final_date)
2019-12-24 00:00:00

And last convert output to python object dates:

print (final_date.date())
2019-12-24

Or to strings:

print (final_date.strftime('%Y-%m-%d'))
2019-12-24
like image 76
jezrael Avatar answered Dec 24 '25 12:12

jezrael


Use Series.strftime:

final_date = (pd.datetime.now().date() - pd.Timedelta(days = 30)).strftime('%Y-%m-%d')
#'2019-12-24' 
like image 35
ansev Avatar answered Dec 24 '25 10:12

ansev



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!