Home > Net >  Python panda data frames datatime only shows date or time. How to show both?
Python panda data frames datatime only shows date or time. How to show both?

Time:11-16

How can I show both the date and time in my 'Time' column inside the csv file? I have shown some different examples of what I am seeing?

where df 'Time' looks like

"2021-11-01 08:00:00"

Example 1. Shows correct in console but not in csv file.

    posix_time = pd.to_datetime(df['Time'], unit='ms')
    df['Time']  = posix_time
    df.to_csv (r'dataframe.csv', index = False, header=True)

0     2021-11-01 08:00:00

 # In csv file ??? why not date and time like above only date ????
      2021-11-01

Example 2. Shows correct in console and correct in file only date.

    posix_time = pd.to_datetime(df['Time'], unit='ms').dt.date
    df['Time']  = posix_time
    df.to_csv (r'dataframe.csv', index = False, header=True)

0      2021-11-01

# In csv file 
       2021-11-01 

Example 3. Shows correct in console and in file only time.

    posix_time = pd.to_datetime(df['Time'], unit='ms').dt.time
    df['Time']  = posix_time
    df.to_csv (r'dataframe.csv', index = False, header=True)

0      08:00:00

# In csv file 
       08:00:00 

CodePudding user response:

You can convert str value to datetime using pd.to_datetime(). For more information of how to set format parameter in pd.to_datetime(), see https://www.dataindependent.com/pandas/pandas-to-datetime/

#file.csv
Time
2021-11-01 08:00:00
2021-11-02 09:00:00
2021-11-03 10:00:00
2021-11-04 11:00:00
2021-11-05 12:00:00
import pandas as pd

filepath = './file.csv'  # to read your csv file
df = pd.read_csv(filepath)
print(df)

# For example, df will be printed look like:
#   Time
#0  2021-11-01 08:00:00
#1  2021-11-02 09:00:00
#2  2021-11-03 10:00:00
#3  2021-11-04 11:00:00
#4  2021-11-05 12:00:00

df['Time'] = pd.to_datetime(df['Time'], format='%Y-%m-%d %H:%M:%S')  # to convert str to datetime format

df.to_csv('result.csv')  # You can see that Time data is saved as "date   time", not just date or time.
  • Related