MultiLevelMenu

Tuesday, July 8, 2014

我的中文寫字

好幾年後寫了一些中文字。不以為我還會寫!

Update: Well it seems, I accidentally deleted the photo of my handwriting from Google Albums while pruning it. Oh well...

Thursday, June 26, 2014

Adding timedelta to a datetime.time

One of Python's strengths is its exhaustive library. And date and time management is an integral part of this, provided by the datetime module. datetime provides the classes datetime, date, time, timedelta and tzoffset.

Logic suggests that timedelta provides a convenient means to represent time intervals which can later be added (or subtracted) from the other types. Trouble is, only datetime class supports operations with timedelta. That is code like this would produce an error:
>>> from datetime import datetime, date, time, timedelta
>>> dt1 = datetime.now()
>>> td1 = timedelta(hours=1)
>>> dt1 + td1
datetime.datetime(2014, 6, 26, 15, 38, 27, 149200) # OK
>>> dt1.time()+td1
Traceback (most recent call last):
  File "", line 1, in 
TypeError: unsupported operand type(s) for +: 'datetime.time' and 'datetime.timedelta'

So how do you add (or subtract) a timedelta object from a time(or date) object? It turns out that a slightly convoluted way exists. Given a time object t1 and timedelta object td1, the following code does the trick.
>>> (datetime.combine(datetime.now().date(), t1)+td1).time()
datetime.time(15, 40, 55, 672503)
There is probably a shorter and better way to accomplish, but at the moment this is what I could come up with.

Monday, June 23, 2014

Convert time string to datetime.time object

I'm still finding my way around the rather vast Python standard library. And today, I discovered a quick way to convert a pure time string (of format HH:MM[:SS]) into a standard datetime.time object.
datetime.strptime('08:00', '%H:%M').time()
That's it! A single, rather short line of code does the job.

The trick here is that the classmethod datetime.strptime() creates a datetime object with default values for the missing parameters. So the above code creates a datetime object with date set to 1900/1/1 and time set to 8:00AM, with seconds and microseconds set to 0. And from this datetime object we can extract the time component by calling the time() method. Cool!