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 :)
Related
How can I put the current year to a column of dates in a DataFrame.
I have this code that changes the format of a date but I am putting an incorrect year and I want to put the current year, does anyone know how I can do it, thanks in advance.
importpandas as pd
date['Fecha'] = pd.to_datetime(date['Fecha'], format='%m/%d')
Result delivered to me:
Result I want:
try:
import pandas as pd
date['Fecha'] = pd.to_datetime(date['Fecha']+"/2022", format='%m/%d/%Y')
If the 'correct' year is 2022, you can use
date['Fecha'] = pd.to_datetime("2022/" + date['Fecha'], format='%Y/%m/%d')
If you want to update it every year with the current year, you can do:
from datetime import date
pd.to_datetime(str(date.today().year) + date['Fecha'], format='%Y%m/%d')
I am trying to create a rolling rota using openpyxl. Some staff members work a 4 on 4 off rolling shift and I am trying to print "N/A" on the dates they are not working.
So far I have the following code:
from datetime import date
today = date.today()
I have tried the following code:
if today == "2022-02-21":
sheet["D13"] = "N/A"
This does not seem to print "N/A" in my desired cell.
I hope my query is not too confusing. Any help will be appreciated.
You have to convert the string to date. probably you will have to iterate over that column and convert it to date, or you can go with the solution offered by mwo.
from datetime import datetime
your_date = '2022-02-21'
date_obj = datetime.strptime(your_date, '%Y-%m-%d')
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.
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
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