How to include a dynamic date in a string - python

I'm trying to write a daily csv file but would like the title of the csv file to specify today's date.
It seems to be failing every time but I'm sure there's an easy way to do this..?
Hopefully this isn't a duplicate but can't seem to find another question similar.
At the minute I've just tried this;
from datetime import date
morningupdate.to_csv('morningupdate' + '_' + date.today() '.csv')
My brain is completely broken with this, any help much appreciated!

Does this solve your problem?
from datetime import date
morningupdate.to_csv(f'morningupdate_{date.today()}.csv')

You are trying to concatenate string with a datetime object.
You can use f string to manage the problem:
from datetime import date
path = f'morningupdate_{date.today()}.csv'
morningupdate.to_csv(path)

Related

Python xlwings - TypeError: must be real number, not Timedelta

I have a pandas dataframe containing columns in timedelta64[ns] format.
For this project I cannot use df.to_excel() and I need to import the dataframe via xlwings so that it prints into existing Excel Workbook and keeps its format.
When I try the usual:
workbook_sablona_dochazka.sheets[zamestnanec].range('A1').options(index=False).value = individual_dochazka_zamestnanec
I receive error:
TypeError: must be real number, not Timedelta
Is there a way to format my timedelta64[ns] so that xlwings would be able to import the dataframe in? I need to preserve my time values so that it becomes 12:30:00 in Excel again after xlwings import and maybe some after-formatting inside the Excel itself.
I tried:
individual_dochazka_zamestnanec['Příchod do práce'] = individual_dochazka_zamestnanec['Příchod do práce'].values.astype(float)
This worked around the error but imported columns had totally out of sense numbers.
Any idea how to work around this?
Thank you very much in advance!
If the error says it's a "TimeDelta", then you have to ask delta relative to what? Usually a TimeDelta indicates something like "three hours" or "minus two days". You say you'd like the output to be "12:30:00" is that an actual time or does it mean 12 hours 30 minutes and no seconds?
You could try making the TimeDelta relative to "the beginning of time" so that it's a date which can be imported into xlwings but is formatted like a time as suggested here.
Just managed to figure it out.
The trick was to first format timedelta64[ns] columns as string and then trim it a bit with .map(lambda x:str(x)[7:])) so that I would get that nice time only stamp.
individual_dochazka_zamestnanec['Počet odpracovaných hodin celkem'] = ((individual_dochazka_zamestnanec['Počet odpracovaných hodin celkem']).astype(str)).map(lambda x: str(x)[7:])
To my surprise, Excel accepted this without issue which is exactly what I needed.
Hope this helps someone, sometime.
Cheers!

Find max date less than today

I’m trying to locate the current date (in this example the date was 1/15/2021) across all columns and return the result in the “current status” column.
The logic behind this in excel is max(if(B2:E2<=“1/15/2021”,B2:E2))
I’m not sure how to work this out through python
Thanks in advance
I would just do this
from datetime import datetime as dt
df['current status'] = dt.now().date()
this would be the easiest way

Adding a duration to a start time string to get a finish time?

I have a string called startTime and I want to add a duration (that's in minutes) to get a finishTime.
Here's some sample data:
startTime : 10:15
duration: 90
In python, what's the best way to add that duration so that the finishTime would be 11:45?
Thank so much, any help much appreciate.
Try this:
import datetime
d = datetime.datetime.strptime("10:12","%H:%m") + datetime.timedelta(minutes=90)
new = d.strftime('%H:%m')
new will be 11:45.
I recommend using pandas for tasks like this, since it is much more intuitive to use than using the datetime module directly.
import pandas as pd
startTime = '10:15'
duration = '90'
finishTime = (pd.to_datetime(startTime , format='%H:%M')
+ pd.to_timedelta(duration + 'min')).strftime(format='%H:%M')
As pointed out by Torxed and shmee, pandas is not a built-in module and it is fairly large with around 70MB, thus it may not be suitable for everyone.
But since pandas is imho the best tool to process time series data and since the question looked like something which is commonly needed when processing time series, I thought a solution with pandas might be interesting/of use.
You could use pd.to_datetime in order to convert the strings to datetime objects, and add the minutes using pd.to_timedelta. Finally convert the datetime to the desired format using strftime:
import pandas as pd
(pd.to_datetime( '10:15', format='%H:%M') + pd.to_timedelta(90, unit='m')).strftime('%H:%M')
#'11:45'

Python converto datetime.isoformat(datetime.utcnow()) to mysql datetime format?

I have a python script that generates a datetime string using this line of code:
data['timestamp'] = datetime.isoformat(datetime.utcnow())
That generates something like the following:
2017-05-24T04:08:09.530033
How do I convert that to "MYSQL insertable" datetime format in a clean way?
Thanks!
Try to use MySQL's STR_TO_DATE() function to parse the string that you're attempting to insert.
I hope this may help you
You can specify any type of format like this depending on the one you `ve set in mysql
data['timestamp'] =pd.to_datetime(data['timestamp'] , format='%d%b%Y:%H:%M:%S.%f')
First off, it looks like you ran from datetime import * rather than import datetime. That's tempting because it lets you type less when you want to refer to parts of the module, but it can get you into name collision issues later. An alternative with less typing is something like import datetime as dt, that way later you can just use dt.datetime. This will make your code cleaner.
MySQL accepts several date formats, which can be read about in detail here. In particular:
The DATETIME type is used for values that contain both date and time
parts. MySQL retrieves and displays DATETIME values in YYYY-MM-DD HH:MM:SS format.
ISO8601 numbers look just like that! 2017-05-24T04:19:32
So if the only difference is the "T" in the middle instead of a space, just run something like this, assuming you don't change your import statements.
timestamp = str(datetime.isoformat(datetime.utcnow()))
timestamp = timestamp.replace("T", " ")
data['timestamp'] = timestamp

python calculate time attendance to file CSV

I have a csv file containing the pointing personal. of this form:
3,23/02/2015,08:27,08:27,12:29,13:52,19:48
3,24/02/2015,08:17,12:36,13:59,19:28
5,23/02/2015,10:53,13:44
5,25/02/2015,09:05,12:34,12:35,13:30,19:08
5,26/02/2015,08:51,12:20,13:46,18:47,18:58
and I want it cleaning. in this way:
ID, DATE, IN,BREAK_OUT, BREAK_IN, OUT, WORK_TIME
3,Monday 23/02/2015,08:27,12:29,13:52,19:48,08:00hours
3,Tuesday 24/02/2015,08:17,12:36,13:59,19:28,08:00hours
5,Monday 23/02/2015,10:53,NAN,13:44,NAN,2houres
5,Wednesday 25/02/2015,09:05,12:34,13:30,19:08,08hours
can you help me please
think you
I'd suggest you use pandas to import the data from the file
import pandas as pd
pd.read_csv(filepath, sep = ',')
should do the trick, assuming filepath leads to your csv. I'd then suggest that you use the datetime functions to convert your strings to dates you can calculate with (I think you could also use numpys datetime64 types, I'm just not used to them).
import datetime as dt
day = dt.datetime.strptime('23/02/2015', '%d/%m/%Y')
in = dt.datetime.combine(day, dt.datetime.strptime('08:27', '%H:%M').time())
should do the trick. It is necessary, that your in is also a datetime object, not only a time object, otherwise you cannot substract them (which would be the necessary next step to calculate the Worktime.
Is think this should be a bit to get you started, You'll find the pandas documentation here and the datetime documentation here.
If you have further questions, try to ask your question more specific.
This question might help you out: How to split string into column
First, read the whole file and split the columns. Check if there's data or not and write it back into a new file.
If you need additional help, tell us what you tried, what worked for you and what didn't and so on. We won't write a complete program/script for you.

Categories

Resources