How can I use pandas.DataFrame.to_csv to write pandas.Timestamp with milliseconds?

37 Views Asked by At

Assume I have a DataFrame containing column with pandas.Timestamp objects like this:

pandas.Timestamp('2019-12-10T17:16:49.467000000')

How can I specify the date_format argument of the pandas.DataFrame.to_csv function to recieve CSV-file with milliseconds, not microseconds?

I tried this way:

df.to_csv('!test.csv', sep='\t', index=False, date_format='%d.%m.%Y %H:%M:%S.%f')

but it gives string like this: 10.12.2019 17:16:49.467000

I need string like this: 10.12.2019 17:16:49.467

1

There are 1 best solutions below

5
mozway On

You can't directly, but you can pre-process the columns before exporting:

def dt_to_str(s):
    if pd.api.types.is_datetime64_dtype(s):
        return s.dt.strftime('%d.%m.%Y %H:%M:%S.%f').str[:-3]
    return s

df.apply(dt_to_str).to_csv('!test.csv', sep='\t', index=False)

Output:

num date
1   10.12.2019 17:16:49.467