Python module datetime getting Day -1 (D-1) - python

I'm trying to write some code that gets a CSV, but the name of that CSV has the date. For example: "myfile-07-09-2021"
I managed to get today's date file, you know how I can read the CSV day -1 (D-1)?

Use datetime.timedelta:
from datetime import timedelta
(datetime.today() - timedelta(1)).strftime('myfile-%d-%m-%Y.csv')

Related

Is there a way to get the current time zone in the format the Google Calendar API wants in Python?

I'm trying to make a python app to interact with Google Calendar and I need help getting the time zone in the format it wants. I tried datetime.datetime.now(datetime.timezone(datetime.timedelta(0))).astimezone().tzinfo,
but that just returned PST and I need it to be America/Los_Angeles.
Any suggestions?
You can use pytz to localize datetime objects in python.
import datetime
import pytz
today = datetime.datetime.now()
localized = pytz.timezone('America/Los_Angeles').localize(today)
You can change the timezone by changing the value of os.environ["TZ"]:
Sample Code:
import os
import time
os.environ["TZ"] = "America/New_York"
time.tzset()
From there, you can change the format of date by using time.strftime(format)
References:
https://docs.python.org/3/library/datetime.html
https://help.pythonanywhere.com/pages/SettingTheTimezone/

Add current date to end of a filename when exporting using to_excel

When I run my script I would like to export it as an Excel file with the current date tagged onto the end of it, I could put the date in manually but as I run this each day I would like it to use the current date automatically.
So, to just output an normal excel via python/pandas I use:
df.to_excel('myfile.xlsx')
And in my working directory I get an Excel file called "myfile.xlsx".
But I would like today's current date added to the end, so if I ran the script today the file would be called "myfile 24/09/2019.xlsx".
This will get you there and employs string formatting for clean / readable code:
from datetime import datetime as dt
# Create filename from current date.
mask = '%d%m%Y'
dte = dt.now().strftime(mask)
fname = "myfile_{}.xlsx".format(dte)
df.to_excel(fname)
As mentioned in a comment above, some OS use / as a path separator, so I suggest using a dmY (24092019) date format. As shown here
Output:
myfile_24092019.xlsx

Python: finding files (png) with a creation date between two set dates

I am relatively new to Python and im trying to make a script that finds files (photos) that have been created between two dates and puts them into a folder.
For that, I need to get the creation date of the files somehow (Im on Windows).
I already have everything coded but I just need to get the date of each picture. Would also be interesting to see in which form the date is returned. The best would be like m/d/y or d/m/y (d=day; m=month, y=year).
Thank you all in advance! I am new to this forum
I imagine you are somehow listing files if so then use the
os.stat(path).st_ctime to get the creation time in Windows and then using datetime module string format it.
https://docs.python.org/2/library/stat.html#stat.ST_CTIME
https://stackoverflow.com/a/39359270/928680
this example shows how to convert the mtime (modified) time but the same applies to the ctime (creation time)
once you have the ctime it's relatively simple to check if that falls with in a range
https://stackoverflow.com/a/5464465/928680
you will need to do your date logic before converting​ to a string.
one of the solutions, not very efficient.. just to show one of the ways this can be done.
import os
from datetime import datetime
def filter_files(path, start_date, end_date, date_format="%Y"):
result = []
start_time_obj = datetime.strptime(start_date, date_format)
end_time_obj = datetime.strptime(end_date, date_format)
for file in os.listdir(path):
c_time = datetime.fromtimestamp(os.stat(file).st_ctime)
if start_time_obj <= c_time <= end_time_obj:
result.append("{}, {}".format(os.path.join(path, file), c_time))
return result
if __name__ == "__main__":
print "\n".join(filter_files("/Users/Jagadish/Desktop", "2017-05-31", "2017-06-02", "%Y-%m-%d"))
cheers!
See the Python os package for basic system commands, including directory listings with options. You'll be able to extract the file date. See the Python datetime package for date manipulation.
Also, check the available Windows commands on your version: most of them have search functions with a date parameter; you could simply have an OS system command return the needed file names.
You can use subprocess to run a shell command on a file to get meta_data of that file.
import re
from subprocess import check_output
meta_data = check_output('wmic datafile where Name="C:\\\\Users\\\\username\\\\Pictures\\\\xyz.jpg"', shell=True)
# Note that you have to use '\\\\' instead of '\\' for specifying path of the file
pattern = re.compile(r'\b(\d{14})\b.*')
re.findall(pattern,meta_data.decode())
=> ['20161007174858'] # This is the created date of your file in format - YYYYMMDDHHMMSS
Here is my solution. The Pillow/Image module can access the metadata of the .png file. Then we access the 36867 position of that metadata which is DateTimeOriginal. Finally I convert the string returned to a datetime object which gives flexibility to do whatever you need to do with it. Here is the code.
from PIL import Image
from datetime import datetime
# Get the creationTime
creationTime = Image.open('myImage.PNG')._getexif()[36867]
# Convert creationTime to datetime object
creationTime = datetime.strptime(creationTime, '%Y:%m:%d %H:%M:%S')

Changing to MYSQL compliant date format using python

I currently have a csv file containing a column of dates that is formatted as dd/mm/yyyy but i want to change it to yyyy/mm/dd
I have written the code below:
import csv
csv_in = open('news.csv','rb')
for rows in csv.reader(csv_in):
value = rows[0]
day= value[:2]
year= value[-4:]
month= value[3:5]
edited = year +'/'+month+'/'+day
rows[0] = edited
writer =csv.writer(open('newsedit.csv', 'wb'))
writer.writerow(rows)
for some reason the code above will only write one row and stop and i can't seem to figure out why this is happening.
Try convert the date by datetime module.
import datetime
datetime.datetime.strptime("25/01/2013", '%d/%m/%Y').strftime('%Y/%m/%d')
The strptime function loads a string to datetime object while strftime converts the datetime to another format as string.
It is because you keep initializing a new writer in each iteration. This causes that the output is being replaced over and over again. You should create a writer object only once, then you can use its writerow() method repeatedly.
(Btw. there is a nice datetime module that makes working with dates easy...)

Python pandas convert given local date time to time stamp with local time zone without day light saving

Following code is my code.
import pandas as pd
pd.to_datetime("2015-11-18 15:30:00+05:30").tz_localize('UTC').tz_convert('Asia/Kolkata')
it returns following o/p
Timestamp('2015-11-18 16:30:00+0530', tz='Asia/Kolkata')
where as I am expecting o/p as follows
Timestamp('2015-11-18 15:30:00+0530', tz='Asia/Kolkata')
How I can get correct timestamp?

Categories