[Tutor] Send Hex

Mark Tolonen metolone+gmane at gmail.com
Sat Dec 19 05:10:36 CET 2009


"Григор" <grigor.kolev at gmail.com> wrote in message 
news:acd355e80912180634l1c7a545fo7be9d5e99138bd08 at mail.gmail.com...
> Hi
> Can I send date and time like Hex in to the Serial port or file.
>
> ------------------------------------
> from time import *

It preferable to just use "import time"

    import time

> def TimeMake():
>     '''Formating time and data (dd-mm-yy hh:mm) and change it like 
> ASCII'''
>     Time=list(localtime())  #get Time and Date
>     Time[0]=str(Time[0])    #Make (yy) str
>     Time = '%02d-%02d-%s %02d:%02d' % (Time[2], Time[1], Time[0][2:],
> Time[4], Time[5]) #Formating (dd-mm-yy hh:mm)

The previous lines have a bug ("dd-mm-yy mm:ss" is the result).  A less 
error-prone version is:

    Time = time.strftime('%d-%m-%y %H:%M',localtime())

>     TimeHex = []
>     for i in Time:      #Take ASCII
>         TimeHex.append(ord(i))
>     Time =[]
>     for i in TimeHex:       #Make ASCII in hex format
>         Time.append(hex(i))
>     return Time
> Time=TimeMake()
> #When I write it in the some file is a string but must to be like hex
> ------------------------------------


The resulting string from strftime *can* be sent directly to a serial port 
or file.  Each character in the string is a byte of data.  If you actually 
need to send hexadecimal characters as text, the binascii module has 
hexlify:

    >>> import binascii
    >>> import time
    >>> binascii.hexlify(time.strftime('%d-%m-%y %H:%M',localtime()))
    '31382d31322d30392032303a3039'

-Mark




More information about the Tutor mailing list