0

I have a csv file with a column named timestamps that has timestamps as follows:
2023-01-26 06:00:00+00:00

I would like to convert the timestamps col into datetime as it currently is an object.

When I run the following code

time = df_usage.iloc[i][timestamps]    
time = datetime.datetime.strptime(time, '%Y-%m-%d %H:%M:%S+')

I get ValueError: unconverted data remains: 00:

After seconds is milliseconds but Python does not appear to have a millisecond directive. Does anyone have a suggestion for a workaround or a simple way to eliminate all time after seconds in the timestamp column? (i.e. turn 2023-01-26 06:00:00+00:00 into 2023-01-26 06:00:00)?

Libra
  • 2,544
  • 1
  • 8
  • 24
  • Pandas has a convenient function for this: `pd.to_datetime()` can be applied across the series. https://pandas.pydata.org/pandas-docs/stable/reference/api/pandas.to_datetime.html – SNygard Apr 24 '23 at 16:35
  • 1
    Your format string doesn't have an entry for the timezone offset portion at the end, so it's complaining about the trailing `00:00`. – Abion47 Apr 24 '23 at 16:37
  • Does this answer your question? [ValueError when using strptime to get a datetime object](https://stackoverflow.com/questions/6707398/valueerror-when-using-strptime-to-get-a-datetime-object) – mkrieger1 Apr 24 '23 at 16:46

1 Answers1

3

Use %z to parse the timezone information (+00:00):

>>> from datetime import datetime
>>> string = "2023-01-26 06:00:00+00:00"
>>> datetime.strptime(string, '%Y-%m-%d %H:%M:%S%z')
datetime.datetime(2023, 1, 26, 6, 0, tzinfo=datetime.timezone.utc)
treuss
  • 1,913
  • 1
  • 15