How to create a date string list in yyyymmdd format using Python Pandas?

I need a list of date ranges in which each element is a string of the format 'yyyymmdd' , for example: ['20130226','20130227','20130228','20130301','20130302'] .

I can use pandas for this:

 >>> pandas.date_range('20130226','20130302') <class 'pandas.tseries.index.DatetimeIndex'> [2013-02-26 00:00:00, ..., 2013-03-02 00:00:00] Length: 5, Freq: D, Timezone: None 

But this is DatetimeIndex, and I need to do some additional format conversion, and how to do it in a neat way?

+4
source share
3 answers

Or using a list comprehension:

 [d.strftime('%Y%m%d') for d in pandas.date_range('20130226','20130302')] 
+8
source

Using format :

 >>> r = pandas.date_range('20130226','20130302') >>> r.format(formatter=lambda x: x.strftime('%Y%m%d')) ['20130226', '20130227', '20130228', '20130301', '20130302'] 

or using map :

 >>> r.map(lambda x: x.strftime('%Y%m%d')) array(['20130226', '20130227', '20130228', '20130301', '20130302'], dtype=object) 
+12
source

For Just a daterange , pandas will be redundant when you again have to reformat the date using datetime . The following solution just uses datetime to serve your purpose

 import datetime def date_range(start_dt, end_dt = None): start_dt = datetime.datetime.strptime(start_dt, "%Y%m%d") if end_dt: end_dt = datetime.datetime.strptime(end_dt, "%Y%m%d") while start_dt <= end_dt: yield start_dt.strftime("%Y%m%d") start_dt += datetime.timedelta(days=1) [e for e in date_range('20130226','20130302')] ['20130226', '20130227', '20130228', '20130301', '20130302'] 
+1
source

Source: https://habr.com/ru/post/1501167/


All Articles