Home > database >  Convert datetime to int seconds microseconds
Convert datetime to int seconds microseconds

Time:11-17

I have a series of strings like '1970-01-01 00:00:00.000002913'. How can I convert this series to obtain juste the int number after "." : 2913. Thank all !!

CodePudding user response:

You can use pandas.Series.dt.nanosecond/microseconds:

s = pd.Series(['1970-01-01 00:00:00.000002913'], dtype='datetime64[ns]')
s.dt.microsecond*1000 s.dt.nanosecond

output:

0    2913
dtype: int64

CodePudding user response:

If you have a pandas series made of strings like the one you show. I believe the most efficient solution would be to use a list comprehension and assign it to a new series, for example:

df['Microsecond'] = [x.split('.')[1] for x in list_of_values]

However if you want a more pandas-ian approach, then you can try using:

df['Microsecond'] = df['date'].str.split('.').str[0].astype(int)

Why does the list comprehension approach work? Because for a single value what you are requesting can be done used int and `.split('.').

int('1970-01-01 00:00:00.000002913'.split('.')[1])

Returns:

2913

CodePudding user response:

If all you have is a string, then just parse it:

s = "1970-01-01 00:00:00.000002913"
value = int(s.rsplit(".", 1)[1])

str.rsplit splits the string starting from the right, and it takes a number of times to split as parameter, so rsplit(".", 1) does the least required work.

Then you just convert that to an int.

  • Related