简体   繁体   中英

Python Pandas to_datetime removes underscore

In my application time is stored in this manner:

05-04-2017_12:28:26.758369

So I wrote:

df[timestamp_lbl] = pd.to_datetime(df[timestamp_lbl],
                                   format="%d-%m-%Y_%H:%M:%S.%f")

When I print df[timestamp_lbl], I get:

05-04-2017 12:28:26.758369

The underscore is now missing. What am I doing wrong? Thanks!

Note: I need the column to have a datetime64 and not a string.

The format argument only tells to_datetime what kind of syntax to expect when it's parsing a date string. But once it's converted to a Pandas Datetime object, its printed representation is always the same. If you need to print out its value at some point, you can use the .strftime() method without changing its dtype :

ts = "05-04-2017_12:28:26.758369"
tsobj = pd.to_datetime(ts,format="%d-%m-%Y_%H:%M:%S.%f")

print(tsobj.strftime("%d-%m-%Y_%H:%M:%S.%f"))
'05-04-2017_12:28:26.758369'

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM