Manipulating dates in python
From raju
add days to date
get today's date as YYYYMMDD
get tomorrow's date as YYYYMMDD
from datetime import datetime from dateutil.relativedelta import relativedelta tomorrow = (datetime.today() + relativedelta(days=1)).strftime('%Y%m%d') print(tomorrow)
Sample run:
$ ipython In [1]: from datetime import datetime ...: from dateutil.relativedelta import relativedelta ...: tomorrow = (datetime.today() + relativedelta(days=1)).strftime('%Y%m%d') ...: print(tomorrow) 20190124
get current time as YYYYMMDD_HHMMSS
extract YYYYMMDD from a string
tags | extract date from filename, using re.split
Say we have files of the form foo_YYYYMMDD.csv, the idea here is extract YYYYMMDD from those file names.
In [1]: import re ...: file_name = 'foo_20180929.csv' ...: file_splits = re.split('(\d{8})', file_name, 1) ...: file_splits Out[1]: ['foo_', '20180929', '.csv'] In [2]: file_splits[1] Out[2]: '20180929'
See also:
useful documentation links
- https://wiki.python.org/moin/WorkingWithTime - has a venn diagram to convert between different formats.
extract hh:mm:ss from current time
tags | convert time to hh:mm:ss, hh mm ss
import time time.strftime('%H:%M:%S', time.localtime())
Out[1]: '15:08:38'
See also:
from datetime import datetime datetime.now().strftime("%H:%M:%S")
Out[2]: '15:09:00'
convert time in seconds to tuple
>>> a = time.time() >>> print(a) 1549399037.6978667 >>> time.localtime(a) time.struct_time(tm_year=2019, tm_mon=2, tm_mday=5, tm_hour=15, tm_min=37, tm_sec=17, tm_wday=1, tm_yday=36, tm_isdst=0) >>> time.gmtime(a) time.struct_time(tm_year=2019, tm_mon=2, tm_mday=5, tm_hour=20, tm_min=37, tm_sec=17, tm_wday=1, tm_yday=36, tm_isdst=0)
See also:- https://wiki.python.org/moin/WorkingWithTime
Get all weekdays between two dates
- If start and end dates are known
import pandas as pd week_days = [dt.strftime('%Y%m%d') for dt in pd.date_range('20191225', '20200101') if dt.weekday() < 5] print(week_days) ['20191225', '20191226', '20191227', '20191230', '20191231', '20200101']
- If start date and offset are known
import pandas as pd week_days = [dt.strftime('%Y%m%d') for dt in pd.date_range('20191225', periods=8) if dt.weekday() < 5] print(week_days) ['20191225', '20191226', '20191227', '20191230', '20191231', '20200101']
- If end date and offset are known
import pandas as pd week_days = [dt.strftime('%Y%m%d') for dt in pd.date_range(end='20200101', periods=8) if dt.weekday() < 5] print(week_days) ['20191225', '20191226', '20191227', '20191230', '20191231', '20200101']
Ref:-
see also:-
Convert YYYYMMDD to datetime object
from datetime import datetime a = '20190205' date = datetime.strptime(a, '%Y%m%d')
Output
>>> date datetime.datetime(2019, 2, 5, 0, 0)
Convert_YYYYMMDD_to_YYYY-MM-DD
Convert YYYYMMDD to epoch timestamp
$ ipython In [1]: from time import mktime, strptime ...: cob='20190103' ...: epoch = mktime(strptime(cob, '%Y%m%d')) ...: print(epoch) 1546491600.0
See also
- Another example - github.com/KamarajuKusumanchi
Convert excel days to datetime
get the beginning and end dates of a month
To get the first date
>>> from datetime import datetime >>> a = datetime.strptime('20160905', '%Y%m%d') >>> a datetime.datetime(2016, 9, 5, 0, 0) >>> b = a.replace(day=1) >>> b datetime.datetime(2016, 9, 1, 0, 0) >>> a datetime.datetime(2016, 9, 5, 0, 0)
To get the last date
>>> from datetime import datetime >>> import calendar >>> a = datetime.strptime('20160905', '%Y%m%d') >>> a datetime.datetime(2016, 9, 5, 0, 0) >>> b = a.replace(day = calendar.monthrange(a.year, a.month)[1]) >>> b datetime.datetime(2016, 9, 30, 0, 0) >>> a datetime.datetime(2016, 9, 5, 0, 0)
Ref:- search for datetime.replace in https://docs.python.org/2/library/datetime.html
add years
from datetime import datetime, timedelta from dateutil.relativedelta import relativedelta cur_date = datetime.strptime('20160301', '%Y%m%d') two_days_ago = cur_date + relativedelta(days=-2) one_year_ago = cur_date + relativedelta(years=-1) print(cur_date) print(two_days_ago) print(one_year_ago)
Output
2016-03-01 00:00:00 2016-02-28 00:00:00 2015-03-01 00:00:00
Ref:-
diffdays
If date is available as year, month, day
In [1]: from datetime import datetime ...: (datetime(2019, 8, 17) - datetime(1899, 12, 30)).days Out[1]: 43694
If date is available as a YYYYMMDD string
In [1]: from datetime import datetime ...: (datetime.strptime('20180602', '%Y%m%d') - datetime.strptime('20180418', '%Y%m%d')).days Out[1]: 45
In practice
>>> d1 = '20180418' >>> d2 = '20180602' >>> from datetime import datetime >>> fmt = '%Y%m%d' >>> dt1 = datetime.strptime(d1, fmt) >>> dt2 = datetime.strptime(d2, fmt) >>> delta = dt2 - dt1 >>> print delta 45 days, 0:00:00 >>> print delta.days 45