Python Openpyxl writing date to excel as short date - python

I am trying to write dates to an excel file using Openpyxl. I am using the following lines to write the date.
dttm = datetime.datetime.strptime(ls25Dict[cell.value][2], "%m/%d/%Y" )
ws1['B'+ str(cell.row)].value = dttm
This writes the date to excel but in the wrong format. This is the output:
2018-01-09 0:00:00
I am trying to get it to be 1/9/2018. Basically change the format to Short Date in excel.
Anyone know how to change it before the date is written to excel?

In Excel you always have to provide your own format for dates and times, because these are stored as serials. openpyxl defaults to ISO formats for minimal ambiguity.

Related

Convert xlsx to csv while dropping sheets and keeping date formats

I have a .xlsx file that I want to convert to .csv file. I have done a demo file as shown in the screenshot. In the .xlsx file, I have 3 sheets and I want to keep the last sheet only. In addition, I want to preserve my dates in a MM/DD/YYYY format.
Found a few solutions here and there on converting then dropping sheets or vice versa. The closest I have come to is using the solution from this link :
But it doesn't keep the date format of MM/DD/YYYY and instead converts it to numbers e.g. 44079. Tried searching solution to convert the numbers to date but there is nothing on this.
Can anyone help me with this? I can provide more clarification if needed.
I am coding in Python.
Hi I solved my own question by using the answer from this Python using pandas to convert xlsx to csv file. How to delete index column?
In addition, because the date is converted into something, not I want in the converted .csv filee.g.
05-09-2020 00:00:00
I used pandas and load the converted csv file to a dataframe. From there I used df['date made'] = pd.to_datetime(df['date made']) to convert the date from an object to datetime. After that I used df['date made'] = df['date made'].dt.strftime(%m/%d/%Y) to get
09/05/2020
which is the date format I wanted. I repeat the steps for Date Due as well.
Hope this helps those who are looking to convert .xlsx to .csv and do some formatting on the date.

strptime not changing date fomat in Excel

I am reading a table and writing to CSV. I have some columns where I want to change the date format. Below is some code I have
for row in out[1]:
dt = datetime.datetime.strptime(row[18], '%Y-%m-%d %H:%M:%S.%f')
row[18] = dt.strftime('%Y-%m-%d)
print(row[18])
It does seem to change the date format to what I'm looking for because the print statement shows as much, but when I open the excel sheet that it wrote, the date format is like 11/12/2019 instead of 2020-11-12.
Any advice? I'm trying to prevent manually changing the format date once opening excel
Most likely, what Excel shows you is not what the underlying data is. Excel auto formats fields when it displays them. Hence, if it opens a CSV and sees 2020-11-12 it will recognize it is a date and display it for you as a formatted date field. If you want to save a field as TEXT that Excel will know is TEXT, then the cell has to start with a " ' ". Try adding this:
row[18] = dt.strftime('\'%Y-%m-%d')

Convert timestamp to datetime.time python

I am working on a dataset which contains the time between various operations in python. The original format of time data is hh:mm. When I read the data in python from excel, it is showing timestamp. for example, the time in excel sheet is 82:35 but python is reading as 1900-01-03 10:35:00. So I want the original values that is time format.
datetime.time(82, 35)
Timestamp('1900-01-01 00:10:00')
I tried to convert into datetime but it shows error.

Python pandas dataframe "Date" Index different format in xlsx and csv

I have an xlsx file with multiple tabs, each tab has a Date column in the format of MM/DD/YYYY
Read each tab into a pandas dataframe, applied some operations on each tab, and then write the dataframe back into two formats: xlsx and csv
In the xlsx file, the Date column (index) becomes a format that has the time attached: 1/1/2013 12:00:00 AM, while the Date column in the csv file remains unchanged: MM/DD/YYYY
How can I make sure the Date column in the xlsx file maintains the same format MM/DD/YYYY?
You are seeing the datetime in the default pandas Excel datetime format. However, you can easily set it to whatever you want:
# Set the default datetime and/or date formats.
writer = pd.ExcelWriter("pandas_datetime.xlsx",
engine='xlsxwriter',
date_format='mm/dd/yyy',
datetime_format='mm/dd/yyyy')
# Convert the dataframe to an XlsxWriter Excel object.
df.to_excel(writer, sheet_name='Sheet1')
See a full example in the XlsxWriter docs: Example: Pandas Excel output with date times.
You can convert the date to a string. If the date is in the index, you could do:
df.set_index(df.index.map(lambda x: x.strftime('%m/%d/%Y'))).to_excel()

Converting datetime to be mysql format using python

I am trying to convert a date format in Excel to be formatted such that it can be read into a MySQL database. I am using python to process the date column, export it back into a csv file and then dump it into a MySQL table.
Here is how the date column look like :
Date
6/10/13
6/17/13
6/24/13
I want it to be in the format : 2013-06-10 or ("%Y-%m-%d")
Here is my code:
import datetime
import csv
def read(filename):
new_date=[]
cr = csv.reader(open(filename,"rU").readlines()[1:], dialect='excel')
for row in cr:
# print row[0]
cols=datetime.datetime.strptime(row[0] , "%m/%d/%y" )
newcols=cols.strftime("%Y-%m-%d")
# print newcols
new_date.append(newcols)
print new_date[0]
with open('new_file.csv', 'wb') as f:
writer = csv.writer(f)
for date in new_date:
writer.writerow([date])
The code runs, but when i open the new_file.csv, the date column automatically reverts back to the old format in excel.
How can i change this?
Thanks,
Have you tried opening the .csv in a simple text editor (like notepad, for example) to see if the date is being printed to that file correctly? My guess is that Excel, which has the ability to recognize dates, is just reformatting it to it's default date format when you open the file, and that if you open your .csv file in a simple text editor to check, you'll see that your code has correctly reformatted the dates in the csv.
(By default, Excel formats dates like you specify in Control Panel, and you can change your default date formatting in Control Panel to change Excel's default formatting.)
You can change the way that Excel formats dates as described here in the documentation.
Select the cells you want to format.
Press CTRL+1.
In the Format Cells box, click the Number tab.
In the Category list, click Date.
You can create a custom date format from this menu if the format you see is not there. Details here.

Categories

Resources