Home > Net >  Change format of date in pandas table
Change format of date in pandas table

Time:01-02

EDIT: I have edited my question as the previous one was unnecessarily problematic.

Is it possible to change the datetime format in the code where the table is built? I understand that the general format is %Y-%m-%d, but I would like for the dates to be in %d-%m-Y format. One of the CSV files I built using this exact code prints in %d-%m-%Y but the other tables print in %Y-%m-%d, I honestly don't understand how ... Here is the code for the table:

import pandas

start_date = "1/1/2022"
end_date = "31/12/2022"
list_of_date = pandas.date_range(start=start_date, end=end_date)
df = pandas.DataFrame(list_of_date)
df.columns = ["Date/Time"]
df["8:00"] = 100
df["9:00"] = 100
df["10:00"] = 100
df["11:00"] = 100
df["12:00"] = 100
df["13:00"] = 100
df["14:00"] = 100
df["15:00"] = 100
df["16:00"] = 100
df["17:00"] = 100
df.to_csv(
    r"Centres"   "\\"   vac_postcode   "\\"   vac_center   "\\"   "slots.csv",
    index=False,
)

Thanks

CodePudding user response:

First, change the type of "Date/Time" column to datetime, then change the formatting, like this:

import pandas as pd

df["Date/Time"] = pd.to_datetime(df["Date/Time"], format="%d/%m/%Y")
df["Date/Time"] = df["Date/Time"].dt.strftime("%d-%m-%Y")

df.to_csv(
    "slots.csv",
    index=False,
)

Then:

    Date/Time  8:00  9:00  10:00  11:00  12:00  13:00  14:00  15:00  16:00  17:00
0  01-01-2022   100   100    100    100    100    100    100    100    100    100
1  02-01-2022   100   100    100    100    100    100    100    100    100    100
2  03-01-2022   100   100    100    100    100    100    100    100    100    100
3  04-01-2022   100   100    100    100    100    100    100    100    100    100
4  05-01-2022   100   100    100    100    100    100    100    100    100    100
  • Related