subtract a day from a python date
Problem
When working with dates, I prefer the order yyyy-mm-dd (e.g. 2015-07-10). Its main advantage is that if you use it as a prefix and sort your entries, you get them in chronological order. (Another advantage is that in my home country we use this order, so this is much closer to my thinking).
So, I faced the following problem: having a date as a string (“2015-07-10”), calculate the date one day before and produce a string again (“2015-07-09”).
Solution
>>> from datetime import datetime, timedelta >>> date = "2015-07-10" >>> today = datetime.strptime(date, '%Y-%m-%d') >>> today datetime.datetime(2015, 7, 10, 0, 0) >>> yesterday = today - timedelta(days=1) >>> yesterday datetime.datetime(2015, 7, 9, 0, 0) >>> yesterday.strftime('%Y-%m-%d') '2015-07-09'
Links
- http://stackoverflow.com/questions/466345/converting-string-into-datetime
- http://stackoverflow.com/questions/441147/how-can-i-subtract-a-day-from-a-python-date
Remark
Back to dates: if I need to write a date in English, I write it like this: “May 12, 1984”. Avoid “05-12-1984”, because what is it? May 12? Or December 5? God knows only.
Simple JSON time service (with timezone support)
Main page: http://json-time.appspot.com
Default UTC time: http://json-time.appspot.com/time.json
Current time in Budapest: http://json-time.appspot.com/time.json?tz=Europe/Budapest
Python’s strftime directives
Python’s strftime directives is a thing that I don’t always need, but when I do, I get frustrated finding it on the net. So here is a shortcut: http://strftime.org/.
I also copy/paste it here for future references:
%a Locale’s abbreviated weekday name. %A Locale’s full weekday name. %b Locale’s abbreviated month name. %B Locale’s full month name. %c Locale’s appropriate date and time representation. %d Day of the month as a decimal number [01,31]. %f Microsecond as a decimal number [0,999999], zero-padded on the left %H Hour (24-hour clock) as a decimal number [00,23]. %I Hour (12-hour clock) as a decimal number [01,12]. %j Day of the year as a decimal number [001,366]. %m Month as a decimal number [01,12]. %M Minute as a decimal number [00,59]. %p Locale’s equivalent of either AM or PM. %S Second as a decimal number [00,61]. %U Week number of the year (Sunday as the first day of the week) as a decimal number [00,53]. All days in a new year preceding the first Sunday are considered to be in week 0. %w Weekday as a decimal number [0(Sunday),6]. %W Week number of the year (Monday as the first day of the week) as a decimal number [00,53]. All days in a new year preceding the first Monday are considered to be in week 0. %x Locale’s appropriate date representation. %X Locale’s appropriate time representation. %y Year without century as a decimal number [00,99]. %Y Year with century as a decimal number. %Z Time zone name (no characters if no time zone exists). %% A literal '%' character. </pre>%a Locale’s abbreviated weekday name. %A Locale’s full weekday name. %b Locale’s abbreviated month name. %B Locale’s full month name. %c Locale’s appropriate date and time representation. %d Day of the month as a decimal number [01,31]. %f Microsecond as a decimal number [0,999999], zero-padded on the left %H Hour (24-hour clock) as a decimal number [00,23]. %I Hour (12-hour clock) as a decimal number [01,12]. %j Day of the year as a decimal number [001,366]. %m Month as a decimal number [01,12]. %M Minute as a decimal number [00,59]. %p Locale’s equivalent of either AM or PM. %S Second as a decimal number [00,61]. %U Week number of the year (Sunday as the first day of the week) as a decimal number [00,53]. All days in a new year preceding the first Sunday are considered to be in week 0. %w Weekday as a decimal number [0(Sunday),6]. %W Week number of the year (Monday as the first day of the week) as a decimal number [00,53]. All days in a new year preceding the first Monday are considered to be in week 0. %x Locale’s appropriate date representation. %X Locale’s appropriate time representation. %y Year without century as a decimal number [00,99]. %Y Year with century as a decimal number. %Z Time zone name (no characters if no time zone exists). %% A literal '%' character.
Create a temporary file with unique name
Problem
I wanted to download an html file with Python, store it in a temporary file, then convert this file to PDF by calling an external program.
Solution #1
#!/usr/bin/env python import os import tempfile temp = tempfile.NamedTemporaryFile(prefix='report_', suffix='.html', dir='/tmp', delete=False) html_file = temp.name (dirName, fileName) = os.path.split(html_file) fileBaseName = os.path.splitext(fileName)[0] pdf_file = dirName + '/' + fileBaseName + '.pdf' print html_file # /tmp/report_kWKEp5.html print pdf_file # /tmp/report_kWKEp5.pdf # calling of HTML to PDF converter is omitted
See the documentation of tempfile.NamedTemporaryFile
here.
Solution #2 (update 20110303)
I had a problem with the previous solution. It works well in command-line, but when I tried to call that script in crontab, it stopped at the line “tempfile.NamedTemporaryFile”. No exception, nothing… So I had to use a different approach:
from time import time temp = "report.%.7f.html" % time() print temp # report.1299188541.3830960.html
The function time() returns the time as a floating point number. It may not be suitable in a multithreaded environment, but it was not the case for me. This version works fine when called from crontab.
Learn more
- tempfile – Create temporary filesystem resources (post by Doug Hellmann with lots of examples)
- Python doc on tempfile
Update (20150712): if you need a temp. file name in the current directory:
>>> import tempfile >>> tempfile.NamedTemporaryFile(dir='.').name '/home/jabba/tmpKrBzoY'
Update (20150910): if you need a temp. directory:
import tempfile import shutil dirpath = tempfile.mkdtemp() # the temp dir. is created # ... do stuff with dirpath shutil.rmtree(dirpath)
This tip is from here.