Archive

Posts Tagged ‘date’

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.

Advertisements
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: , , ,

produce the output of Unix’s date command

April 6, 2012 Leave a comment

Problem
You want to get the same output as Unix’s date command but you don’t want to make an external call. How to produce this output in pure Python?

Solution
I posed this question today on the python-list and I got the following answer from Chris R.:

From POSIX (http://pubs.opengroup.org/onlinepubs/009695399/utilities/date.html):

When no formatting operand is specified, the output in the POSIX locale shall be equivalent to specifying:

   date "+%a %b %e %H:%M:%S %Z %Y"

Therefore:
   from time import strftime
   print strftime("%a %b %e %H:%M:%S %Z %Y")

But note that `date` is locale-sensitive; imitating that would be a
bit more complicated.

Thus, the code snippet:

from time import strftime
print strftime("%a %b %e %H:%M:%S %Z %Y")
# sample output:
# Thu Apr  5 23:55:56 CEST 2012
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: , , ,

date today

October 17, 2010 Leave a comment

Let’s see how to get today’s date in the format yyyymmdd, i.e. {year}{month}{day}. This format has an advantage. If you have several dates like this and you sort them lexicographically, then you get them in chronological order. I often use this format when creating subdirectories in the file system. Most file managers sort them automatically, so I can see them in order.

#!/usr/bin/env python

import datetime

def date_to_str(d):
    return ''.join(str(i) for i in d)

today = datetime.date.today().timetuple()[:3]

print today                 # (2010, 10, 17)
print date_to_str(today)    # 20101017

Here today is a tuple with three elements. The function date_to_str() joins the elements and returns a string. If you use the separator ‘-‘, i.e. '-'.join(...), then you get the following output: 2010-10-17.

Good to know

The form year before month before day is standard in Asian countries, Hungary, Sweden and the US armed forces.

Categories: python Tags: ,