reduce milliseconds precision python

92 views Asked by At

I have this timestamp

2023-07-12 21:12:21.940000

After converting it using :

df_snowflake['last_activity']=df_snowflake['last_activity'].dt.strftime('%Y-%m-%d %H:%M:%S.%f')

I want to reduce the milliseconds precision and get the next datetime :

2023-07-12 21:12:21.940
1

There are 1 answers

2
Sustain Ability On BEST ANSWER

You can use format strings to achieve that.

dt = datetime.datetime.strptime("2023-07-12 21:12:21.94000", '%Y-%m-%d %H:%M:%S.%f')
print(f"{dt:%Y-%m-%d %H:%M:%S}.{dt.microsecond // 1000:03d}")

You can also use string comprehensions like dt[:-3], however in this case you won't be able to deal with 0 milliseconds.

See this link