change the date string into timestamp

Fredrik Lundh fredrik at pythonware.com
Sat Apr 9 06:10:35 EDT 2005


"praba kar" wrote:

> In Php strtotime() will change a date
> string into timestamp.  I want to know which
> python function will  change a date string
> into timestamp.

you might save yourself (and everyone else) some time by looking for
things in the documentation before you post...

> Time stamp means datestring will converted as seconds
>
> example is below
>
> Fri, 8 Apr 2005 09:22:14 +0900 this date value
>
> time stamp is 1112962934

the quickest way to convert a time value to a string is to use the time.ctime()
function:

>>> x = 1112962934
>>> time.ctime(x)
'Fri Apr 08 14:22:14 2005'

to specify a non-standard format, use a format string with the time.strftime
function (or the corresponding datetime functions).  an example:

>>> x = 1112962934
>>> time.strftime("%Y%m%d %H%M%S", time.localtime(x))
'20050408 142214'

see the "time" and "datetime" documentation for details.

the timestamp format you're using is also known as the RFC(2)822 format.  the
"email" package contains several functions to deal with this format:

>>> x = 1112962934
>>> from email.Utils import formatdate
>>> formatdate(x) # default is utc
'Fri, 08 Apr 2005 12:22:14 -0000'
>>> formatdate(x, localtime=1)
'Fri, 08 Apr 2005 14:22:14 +0200'

>>> from email.Utils import parsedate_tz
>>> parsedate_tz(formatdate(x, localtime=1))
(2005, 4, 8, 14, 22, 14, 0, 1, 0, 7200)

for the full story, see:

    http://docs.python.org/lib/module-email.Utils.html

</F> 






More information about the Python-list mailing list