[Tutor] Searching for time in a given string

Mark Tolonen metolone+gmane at gmail.com
Fri Apr 2 05:20:01 CEST 2010


"Judith Flores" <juryef at yahoo.com> wrote in message 
news:27451.74230.qm at web113808.mail.gq1.yahoo.com...
> Hello,
>
>   I was wondering if someone could provide me with the pattern syntax to 
> find the time in a given string. The time usually appears as "14:28:32" 
> (for example) within a string ("Sun Jan 23 14:28:32 1965"). How can I 
> retrieve the time?

The built-in datetime module can parse this type of string:
(http://docs.python.org/library/datetime.html#strftime-and-strptime-behavior)

PythonWin 2.6.5 (r265:79096, Mar 19 2010, 21:48:26) [MSC v.1500 32 bit 
(Intel)] on win32.
Portions Copyright 1994-2008 Mark Hammond - see 'Help/About PythonWin' for 
further copyright information.
>>> s = "Sun Jan 23 14:28:32 1965"
>>> from datetime import datetime
>>> d=datetime.strptime(s,'%a %b %d %H:%M:%S %Y')
>>> d.hour
14
>>> d.minute
28
>>> d.second
32
>>> d.time()
datetime.time(14, 28, 32)
>>> d.date()
datetime.date(1965, 1, 23)
>>> d.ctime()
'Sat Jan 23 14:28:32 1965'

It also knows that date was really a Saturday :^)

-Mark





More information about the Tutor mailing list