User Tools

Site Tools


manipulating_dates_in_python

This is an old revision of the document!


get today's day, month and year

% ipython3
Python 3.9.2 (default, Feb 28 2021, 17:03:44) 
IPython 7.20.0 -- An enhanced Interactive Python. Type '?' for help.

In [1]: 
import datetime
today = datetime.date.today()

In [2]: 
print(today)
2021-08-14

In [3]: 
type(today)
Out[3]: 
datetime.date

In [4]: 
[today.year, today.month, today.day]
Out[4]: 
[2021, 8, 14]

iterate over a range of dates

To iterate on all days including weekends

for dt in pd.date_range('20160226', '20160303'):
  print(dt.strftime('%Y%m%d'))

20160226
20160227
20160228
20160229
20160301
20160302
20160303

To iterate only on weekdays

for dt in pd.date_range('20160226', '20160303'):
  if (dt.weekday() < 5):
    print(dt.strftime('%Y%m%d'))

20160226
20160229
20160301
20160302
20160303

To iterate in reverse chronological order

for dt in pd.date_range('20160226', '20160303')[::-1]:
  if (dt.weekday() < 5):
    print(dt.strftime('%Y%m%d'))

20160303
20160302
20160301
20160229
20160226

To experiment with just one date element

>>> a = pd.date_range('20160226', '20160303')
>>> a[0].strftime('%Y%m%d')
'20160226'

To create a pandas.tslib.Timestamp variable

>>> from datetime import datetime
>>> for dt in pd.date_range('20160929', '20160930')[::-1]:
...     dt == pd.Timestamp(datetime(2016, 9, 29))
...
False
True

>>> type(pd.Timestamp(datetime(2016, 9, 29)))
<class 'pandas.tslib.Timestamp'>

>>> for dt in pd.date_range('20160929', '20160930')[::-1]:
...     type(dt)
...
<class 'pandas.tslib.Timestamp'>
<class 'pandas.tslib.Timestamp'>

tags | convert output from pandas data_range function to YYYYMMDD, date_range reverse order

Ref:-

manipulating_dates_in_python.1658532094.txt.gz · Last modified: 2022/07/22 23:21 by raju