1

My list of timestamps is given below:

time_list = 
[Timestamp('2019-01-24 00:00:00'),
 Timestamp('2019-01-27 00:00:00'),
 Timestamp('2019-01-29 00:00:00'),
 Timestamp('2019-02-08 00:00:00'),
 Timestamp('2019-02-09 00:00:00'),
 Timestamp('2019-02-10 00:00:00')]

I would like to take only the date part and convert it to a string. My code is

aux1 = []
for i in time_list:     
    aux1.append(str(i))
date_list = aux1

Present output is:

date_list = 
['2019-01-24 00:00:00',
 '2019-01-27 00:00:00',
 '2019-01-29 00:00:00',
 '2019-02-08 00:00:00',
 '2019-02-09 00:00:00',
 '2019-02-10 00:00:00']

However the output I want is:

date_list = ['2019-01-24', '2019-01-27', '2019-01-29', '2019-02-08', '2019-02-09', '2019-02-10']

In my code I have used for loop approach but it is not producing the desired answer. Is there a better approach to get my desired date_list?

Al Imran
  • 882
  • 7
  • 29
Msquare
  • 775
  • 7
  • 17

3 Answers3

1

Use Timestamp.strftime in list comprehension or loop:

date_list = [x.strftime('%Y-%m-%d') for x in time_list]

date_list = []
for i in time_list:     
    date_list.append(i.strftime('%Y-%m-%d'))

Or use DatetimeIndex.strftime with converting to list:

date_list = pd.DatetimeIndex(time_list).strftime('%Y-%m-%d').tolist()
print (date_list)
['2019-01-24', '2019-01-27', '2019-01-29', '2019-02-08', '2019-02-09', '2019-02-10']
jezrael
  • 822,522
  • 95
  • 1,334
  • 1,252
  • I preferred your third approach because it does not have any `for` loop. This worked perfectly. Thanks a ton. Can you clarify my doubt, that is, using `for` loop is it a bad code? – Msquare Apr 24 '19 at 11:44
  • 1
    @Msquare - It depends, but short answer is dont use loops, if exist vectorized alternative. More info about this is [here](https://stackoverflow.com/questions/54028199/for-loops-with-pandas-when-should-i-care) – jezrael Apr 24 '19 at 11:48
0

You can use dt.strftime

Ex:

aux1 = []
for i in time_list:     
    aux1.append(i.dt.strftime('%Y-%m-%d'))
date_list = aux1
Rakesh
  • 81,458
  • 17
  • 76
  • 113
0

Try like this:

import dateutil.parser


date_list = ['2019-01-24 00:00:00',
 '2019-01-27 00:00:00',
 '2019-01-29 00:00:00',
 '2019-02-08 00:00:00',
 '2019-02-09 00:00:00',
 '2019-02-10 00:00:00']

for data in date_list:

   dates = dateutil.parser.parse(data).date()
   print(dates)
Sankar guru
  • 935
  • 1
  • 7
  • 16