0

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
FObersteiner
  • 22,500
  • 8
  • 42
  • 72
baddy
  • 369
  • 1
  • 3
  • 23
  • https://stackoverflow.com/questions/66636656/how-to-get-rid-of-milliseconds-for-datetime-in-python. https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.Series.dt.floor.html – Сергей Кох Jul 14 '23 at 08:27
  • Maybe with pandas is better, try something like this: `df['Date'] = pd.to_datetime(df['Date']).dt.time` – Linux Jul 14 '23 at 08:42
  • "*reduce the milliseconds precision*" - to what other precision? Also, what's the desired data type here, a string? A pandas datetime? – FObersteiner Jul 14 '23 at 09:26

1 Answers1

1

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

  • it's much easier here to use [datetime.isoformat](https://docs.python.org/3/library/datetime.html#datetime.datetime.isoformat) with keyword `timespec="milliseconds"`. However, I think OP is using pandas, so this might not apply. – FObersteiner Jul 14 '23 at 09:27
  • Actually I have used 'dt[:-3]' and I am satisfied by the result – baddy Jul 17 '23 at 12:52