Archive

Posts Tagged ‘time’

subtract a day from a python date

July 10, 2015 Leave a comment

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

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.

Categories: python Tags: , , , ,

Simple JSON time service (with timezone support)

Categories: python Tags: , ,

Python’s strftime directives

April 11, 2012 Leave a comment

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.
Categories: python Tags: , , ,

Current date and time

February 25, 2011 Leave a comment
#!/usr/bin/env python

from datetime import datetime

now = datetime.now()
date = datetime.date(now)
time = datetime.time(now)
print "%d-%02d-%02d @ %02dh%02d" % (date.year, date.month, date.day, time.hour, time.minute)

Sample output:

2011-02-25 @ 11h23

Update (20110523)
I wanted to use a timestamp in the name of a temporary file. Here is a slightly modified version of the code above:

...
print "{year}{month:02}{day:02}_{hour:02}{minute:02}{second:02}".format(year=date.year, month=date.month, day=date.day, hour=time.hour, minute=time.minute, second=time.second)
...

Sample output:

20110523_235828
Categories: python Tags: , , ,

Create a temporary file with unique name

February 19, 2011 Leave a comment

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

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.

Categories: python Tags: , , , , , ,