How to keep the delimiters by using df.str.split() with multipe delimiters

Viewed 52

The dataframe I have been working in has a column that indicate datetime with time zone, like that : 2019-01-23T04:30:00+01:00.

                    Horodate
0  2019-01-23T04:30:00+01:00
1  2019-01-23T04:30:00+01:00
2  2019-01-23T04:30:00+01:00
3  2019-01-23T04:30:00-01:00

I woud like to get timezone information and put it into another column called "TimeZone". I could do that by applying this function :

df["TimeZone"] = "+"  + df["Horodate"].str.split('[+]').str[1] 

That works fine:

                    Horodate TimeZone
0  2019-01-23T04:30:00+01:00   +01:00
1  2019-01-23T04:30:00+01:00   +01:00
2  2019-01-23T04:30:00+01:00   +01:00
3  2019-01-23T04:30:00-01:00      NaN

but it is valable only for timezone that starts with "+". I would like to find a way to extract the whole information about time zone,including signal "+" or "-" and get a dataframe that looks like that :

                    Horodate TimeZone
0  2019-01-23T04:30:00+01:00   +01:00
1  2019-01-23T04:30:00+01:00   +01:00
2  2019-01-23T04:30:00+01:00   +01:00
3  2019-01-23T04:30:00-01:00   -01:00

I think I have to pass to split multiple delimeters but the problem is, how to include the delimater at the same time I need to split the string ? I can obtain a good result just slicing the string like that :

df_test["TimeZone"] =  df_test["Horodate"].str[19:] 

but it's not a generical way to do that. Thanks in advance.

3 Answers

How about just string slicing?

In [285]: df["TimeZone"] = df["Horodate"].str[-6:] 

In [286]: df
Out[286]: 
                    Horodate TimeZone
0  2019-01-23T04:30:00+01:00   +01:00
1  2019-01-23T04:30:00+01:00   +01:00
2  2019-01-23T04:30:00+01:00   +01:00
3  2019-01-23T04:30:00-01:00   -01:00

You could also use Series.str.extract with a regex pattern:

df['TimeZone'] =  df['Horodate'].str.extract(r'([+-]\d{2}:\d{2})')

[out]

                    Horodate TimeZone
0  2019-01-23T04:30:00+01:00   +01:00
1  2019-01-23T04:30:00+01:00   +01:00
2  2019-01-23T04:30:00+01:00   +01:00
3  2019-01-23T04:30:00-01:00   -01:00

str.sub allow regexes, so you could do:

df['Timezone'] = df.Horodate.str.replace('(.*)([+-])(.*)', r'\2\3')
Related