hawruh
hawruh

Reputation: 195

Python pandas - Convert string to datetime without a year using pandas.to_datetime()

I have a column in a dataframe which has timestamps and their datatype is object (string):

data_log = pd.read_csv(DATA_LOG_PATH)
print(data_log['LocalTime'])

0      09:38:49 
1      09:38:50 
2      09:38:51 
3      09:38:52 
4      09:38:53
         ...    
Name: LocalTime, Length: 872, dtype: object

Now I try to convert to datetime:

data_log['LocalTime'] = pd.to_datetime(data_log['LocalTime'], format='%H:%M:%S')
print(data_log['LocalTime'])

0     1900-01-01 09:38:49
1     1900-01-01 09:38:50
2     1900-01-01 09:38:51
3     1900-01-01 09:38:52
4     1900-01-01 09:38:53
              ...        
Name: LocalTime, Length: 872, dtype: datetime64[ns]

How do I remove that date there? I just want the time in the format that I specified, but it adds the 1900-01-01 to every row.

Upvotes: 0

Views: 606

Answers (3)

Håken Lid
Håken Lid

Reputation: 23084

You can get the time part of a datetime series with Series.dt.time

print(data_log['LocalTime'].dt.time)

This series will consist of Python standard library datetime.time objects.

Upvotes: 2

Piotr Żak
Piotr Żak

Reputation: 2132

For check the type in specific columns:

print(df['LocalTime'].dtypes) 

to_dateTime func from pandas

https://pandas.pydata.org/docs/reference/api/pandas.to_datetime.html

df['LocalTime'] = pd.to_datetime(df['timestamp'], unit='s')

where: unit='s' defines the unit of the timestamp (seconds in this case)

For taking consider timezones:

df.rimestamp.dt.tz_localize('UTC').dt.tz_convert('Europe/Brussels')

Upvotes: 0

Ostap Orishko
Ostap Orishko

Reputation: 71

You can do it in different ways from the datatype with 1900-01-01:

data_log['LocalTime'] = pd.Series([lt.time() for lt in data_log['LocalTime']])

or using a lambda function:

data_log['LocalTime'] = data_log.LocalTime.apply(lambda x: x.time(), axis = 1)

Upvotes: 1

Related Questions