Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create a list of date string in 'yyyymmdd' format with Python Pandas?

I want a list of date range in which each element is 'yyyymmdd' format string, such as : ['20130226','20130227','20130228','20130301','20130302'] .

I can use pandas to do so:

>>> 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 it is DatetimeIndex and I need to do some extra format transform, so how to do that in a neat way ?

like image 609
bigbug Avatar asked Sep 08 '13 13:09

bigbug


2 Answers

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)
like image 90
falsetru Avatar answered Oct 22 '22 16:10

falsetru


Or using list comprehension:

[d.strftime('%Y%m%d') for d in pandas.date_range('20130226','20130302')]
like image 37
zero323 Avatar answered Oct 22 '22 15:10

zero323