Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

pandas date to string

i have a datetime pandas.Series. One column called "dates". I want to get 'i' element in loop like string.

s.apply(lambda x: x.strftime('%Y.%m.%d')) or astype(str).tail(1).reset_index()['date'] or many other solutions don't work.

I just want a string like '2016-09-16' (first datetime element in series) and not what is currently returned, which is:

 ss = series_of_dates.astype(str).tail(1).reset_index()['date']
"lol = %s" % ss 

lol = 0 2016-09-16\nName: date, dtype: object

I need just:

lol = 2016-09-16

because I need

some string % a , b , s ,d

..... without even '/n' in a, b ,s ...

like image 483
ooolllooo Avatar asked Mar 12 '23 02:03

ooolllooo


2 Answers

I think you can use strftime for convert datetime column to string column:

import pandas as pd

start = pd.to_datetime('2015-02-24 10:00')
rng = pd.date_range(start, periods=10)

df = pd.DataFrame({'dates': rng, 'a': range(10)})  
print (df)
   a               dates
0  0 2015-02-24 10:00:00
1  1 2015-02-25 10:00:00
2  2 2015-02-26 10:00:00
3  3 2015-02-27 10:00:00
4  4 2015-02-28 10:00:00
5  5 2015-03-01 10:00:00
6  6 2015-03-02 10:00:00
7  7 2015-03-03 10:00:00
8  8 2015-03-04 10:00:00
9  9 2015-03-05 10:00:00

s = df.dates
print (s.dt.strftime('%Y.%m.%d'))
0    2015.02.24
1    2015.02.25
2    2015.02.26
3    2015.02.27
4    2015.02.28
5    2015.03.01
6    2015.03.02
7    2015.03.03
8    2015.03.04
9    2015.03.05
Name: dates, dtype: object

Loop with Series.iteritems:

for idx, val in s.dt.strftime('%Y.%m.%d').iteritems():
    print (val)

    2015.02.24
2015.02.25
2015.02.26
2015.02.27
2015.02.28
2015.03.01
2015.03.02
2015.03.03
2015.03.04
2015.03.05
like image 71
jezrael Avatar answered Mar 21 '23 00:03

jezrael


In order to extract the value, you can try:

ss = series_of_dates.astype(str).tail(1).reset_index().loc[0, 'date']

using loc will give you the contents just fine.

like image 40
Thanos Avatar answered Mar 21 '23 00:03

Thanos