4

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 ...

1
  • can you post some sample data and desired output? For example an output of print(s.head(10))... Commented Sep 19, 2016 at 17:35

2 Answers 2

4

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
Sign up to request clarification or add additional context in comments.

Comments

2

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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.