convert date into day in year of a Dataframe in Python - python

I have a Dataframe traindf having Date column with the date in the format "YYYY-MM-DD". I am trying to convert the date in day in the year and append to the year. For ex. "2010-02-05" to "2010036". I got the below code working but want to check if there are any efficient way to get it.
dtstrip = [int('%d%03d' % (datetime.datetime.strptime(dt, fmt).timetuple().tm_year, datetime.datetime.strptime(dt, fmt).timetuple().tm_yday)) for dt in traindf['Date']]
traindf['Date'] = dtstrip

You want something like this?
today = datetime.datetime.now()
print(today.strftime('%Y%j'))
For today the output is:
2017260

Related

I have a list of dates and I want to subtract actual date from each of them to know how many day passed. Is there any fast way to do this?

I know I should import datetime to have actual date. But the rest is black magic for me right now.
ex.
dates = ['2019-010-11', '2013-05-16', '2011-06-16', '2000-04-22']
actual_date = datetime.datetime.now()
How can I subtract this and as a result have new list with days that passed by from dates to actual_date?
If I'm understanding correctly, you need to find the current date, and then find the number of days between the current date and the dates in your list?
If so, you could try this:
from datetime import datetime, date
dates = ['2019-10-11', '2013-05-16', '2011-06-16', '2000-04-22']
actual_date = date.today()
days = []
for date in dates:
date_object = datetime.strptime(date, '%Y-%m-%d').date()
days_difference = (actual_date - date_object).days
days.append(days_difference)
print(days)
What I am doing here is:
Converting the individual date strings to a "date" object
Subtracting the this date from the actual date. This gets you the time as well, so to strip that out we add .days.
Save the outcome to a list, although of course you could do whatever you wanted with the output.

Get previous month date from date stored in string variable

I am extracting the date from a filename and storing it in a string variable. Suppose the filename is CRM_DATA_PUBLIC_20201120_052035.txt, I have extracted the date as 20201120. Now I want to get the previous month's date from this, like 20201020 or just 202010.
I tried using date functions but it is giving error for me.
Could you please help me out here ?
Thanks in anticipation.
Try this: (changes based on a comment)
import datetime
from dateutil.relativedelta import relativedelta
filename = 'CRM_DATA_PUBLIC_20201120_052035.txt'
date = filename.split('_')[3]
#If you want the output to include the day of month as well
date = datetime.datetime.strptime(date, '%Y%m%d')
#If you want only the month
date = datetime.datetime.strptime(date, '%Y%m')
date = date - relativedelta(months=1)
date = str(date.date()).replace('-','')
print(date)
Output:
20201020
You can find your answer here https://stackoverflow.com/a/9725093/10334833
What I get from your question is already answered here but if you are still confused let me know I can help you :)

Create a blank date in python

I want to add a blank column of date of format "%Y-%m-%d" to a dataframe. I tried datetime.datetime.strptime('0000-00-00',"%Y-%m-%d")
But I get an error ValueError: time data '0000-00-00' does not match format '%Y-%m-%d'
How can I create a column of blank date of format "%Y-%m-%d"?
In R following works.
df$date =""
class(df$date) = "Date"
How can I achieve this in Python?
Thank you.
I don't think that's possible with datetime module. The oldest you can go to is answered here:
What is the oldest time that can be represented in Python?
datetime.MINYEAR
The smallest year number allowed in a date or datetime object. MINYEAR is 1.
datetime.MAXYEAR
The largest year number allowed in a date or datetime object. MAXYEAR is 9999.
source: datetime documentation
initial_date = request.GET.get('data') or datetime.min # datetime.min is 1
end_date = request.GET.get('data_f') or datetime.max # datetime.max is 9999

Python Date Index: finding the closest date a year ago from today

I have a panda dataframe (stock prices) with an index in a date format. It is daily but only for working days.
I basically try to compute some price performance YTD and from a year ago.
To get the first date of the actual year in my dataframe I used the following method:
today = str(datetime.date.today())
curr_year = int(today[:4])
curr_month = int(today[5:7])
first_date_year = (df[str(curr_year)].first_valid_index())
Now I try to get the closest date a year ago (exactly one year from the last_valid_index()). I could extract the month and the year but then it wouldn't be as precise. Any suggestion ?
Thanks
Since you didn't provide any data, I am assuming that you have a list of dates (string types) like the following:
dates = ['11/01/2016', '12/01/2016', '02/01/2017', '03/01/2017']
You then need to transform that into datetime format, I would suggest using pandas:
pd_dates = pd.to_datetime(dates)
Then you have to define today and one year ago. I would suggest using datetime for that:
today = datetime.today()
date_1yr_ago = datetime(today.year-1, today.month, today.day)
Lastly, you slice the date list for dates larger than the date_1yr_ago value and get the first value of that slice:
pd_dates[pd_dates > date_1yr_ago][0]
This will return the first date that is larger than the 1 year ago date.
output:
Timestamp('2017-02-01 00:00:00')
You can convert that datetime value to string with the following code:
datetime.strftime(pd_dates[pd_dates > date_1yr_ago][0], '%Y/%m/%d')
output:
'2017/02/01'

How to perform arithmetic operation on a date in Python?

I have a date column in csv file say Date having dates in this format 04/21/2013 and I have one more column Next_Day. In Next_Day column I want to populate the date which comes immediately after the date mentioned in date column. For eg. if date column has 04/21/2013 as date then I want 04/22/2013 in Next_Day column.
We can use +1 in excel but I don't know how to perform this in Python.
Please help me in resolving this.
Using datetime.timedelta
>>> import datetime
>>> s = '04/21/2013'
>>> d = datetime.datetime.strptime(s, '%m/%d/%Y') + datetime.timedelta(days=1)
>>> print(d.strftime('%m/%d/%Y'))
04/22/2013
Same answer as a one-liner. Prints 1 day 1 hour & 30 minutes ago from now:
python -c 'import datetime;print(datetime.datetime.now() - datetime.timedelta(days=1,hours=1,minutes=30))'
2022-02-08 13:11:06.304608

Categories

Resources