How to print a specific string on a specific date using openpyxl - python

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')

Related

How to put the correct year in the date with python?

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')

How can I add a zero to dates in a string so all months are 2 characters? [duplicate]

Using a Python script, I need to read a CVS file where dates are formated as DD/MM/YYYY, and convert them to YYYY-MM-DD before saving this into a SQLite database.
This almost works, but fails because I don't provide time:
from datetime import datetime
lastconnection = datetime.strptime("21/12/2008", "%Y-%m-%d")
#ValueError: time data did not match format: data=21/12/2008 fmt=%Y-%m-%d
print lastconnection
I assume there's a method in the datetime object to perform this conversion very easily, but I can't find an example of how to do it. Thank you.
Your example code is wrong. This works:
import datetime
datetime.datetime.strptime("21/12/2008", "%d/%m/%Y").strftime("%Y-%m-%d")
The call to strptime() parses the first argument according to the format specified in the second, so those two need to match. Then you can call strftime() to format the result into the desired final format.
you first would need to convert string into datetime tuple, and then convert that datetime tuple to string, it would go like this:
lastconnection = datetime.strptime("21/12/2008", "%d/%m/%Y").strftime('%Y-%m-%d')
I am new to programming. I wanted to convert from yyyy-mm-dd to dd/mm/yyyy to print out a date in the format that people in my part of the world use and recognise.
The accepted answer above got me on the right track.
The answer I ended up with to my problem is:
import datetime
today_date = datetime.date.today()
print(today_date)
new_today_date = today_date.strftime("%d/%m/%Y")
print (new_today_date)
The first two lines after the import statement gives today's date in the USA format (2017-01-26). The last two lines convert this to the format recognised in the UK and other countries (26/01/2017).
You can shorten this code, but I left it as is because it is helpful to me as a beginner. I hope this helps other beginner programmers starting out!
Does anyone else else think it's a waste to convert these strings to date/time objects for what is, in the end, a simple text transformation? If you're certain the incoming dates will be valid, you can just use:
>>> ddmmyyyy = "21/12/2008"
>>> yyyymmdd = ddmmyyyy[6:] + "-" + ddmmyyyy[3:5] + "-" + ddmmyyyy[:2]
>>> yyyymmdd
'2008-12-21'
This will almost certainly be faster than the conversion to and from a date.
#case_date= 03/31/2020
#Above is the value stored in case_date in format(mm/dd/yyyy )
demo=case_date.split("/")
new_case_date = demo[1]+"-"+demo[0]+"-"+demo[2]
#new format of date is (dd/mm/yyyy) test by printing it
print(new_case_date)
If you need to convert an entire column (from pandas DataFrame), first convert it (pandas Series) to the datetime format using to_datetime and then use .dt.strftime:
def conv_dates_series(df, col, old_date_format, new_date_format):
df[col] = pd.to_datetime(df[col], format=old_date_format).dt.strftime(new_date_format)
return df
Sample usage:
import pandas as pd
test_df = pd.DataFrame({"Dates": ["1900-01-01", "1999-12-31"]})
old_date_format='%Y-%m-%d'
new_date_format='%d/%m/%Y'
conv_dates_series(test_df, "Dates", old_date_format, new_date_format)
Dates
0 01/01/1900
1 31/12/1999
The most simplest way
While reading the csv file, put an argument parse_dates
df = pd.read_csv("sample.csv", parse_dates=['column_name'])
This will convert the dates of mentioned column to YYYY-MM-DD format
Convert date format DD/MM/YYYY to YYYY-MM-DD according to your question, you can use this:
from datetime import datetime
lastconnection = datetime.strptime("21/12/2008", "%d/%m/%Y").strftime("%Y-%m-%d")
print(lastconnection)
df is your data frame
Dateclm is the column that you want to change
This column should be in DateTime datatype.
df['Dateclm'] = pd.to_datetime(df['Dateclm'])
df.dtypes
#Here is the solution to change the format of the column
df["Dateclm"] = pd.to_datetime(df["Dateclm"]).dt.strftime('%Y-%m-%d')
print(df)

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 calculate the number of year in date column

I've recently start coding with Python, and I'm struggling to calculate the number of years between the current date and a given date.
Dataframe
I would like to calculate the number of year for each column.
I tried this but it's not working:
def Number_of_years(d1,d2):
if d1 is not None:
return relativedelta(d2,d1).years
for col in df.select_dtypes(include=['datetime64[ns]']):
df[col]=Number_of_years(df[col],date.today())
Can anyone help me find a solution to this?
I see that the format of dates is day/month/year.
Given this format is same for all the grids, you can parse the date using the datetime module like so:
from datetime import datetime # import module
def numberOfYears(element):
# parse the date string according to the fixed format
date = datetime.strptime(element, '%d/%m/%Y')
# return the difference in the years
return datetime.today().year - date.year
# make things more interesting by vectorizing this function
function = np.vectorize(numberOfYears)
# This returns a numpy array containing difference between years.
# call this for each column, and you should be good
difference = function(df.Date_creation)
You code is basically right, but you're operating over a pandas series so you can't just call relativedelta directly:
def number_of_years(d1,d2):
return relativedelta(d2,d1).years
for col in df.select_dtypes(include=['datetime64[ns]']):
df[col]= df[col].apply(lambda d: number_of_years(x, date.today()))

Categories

Resources