1

I have the time in this format:

Fri, 19 Dec 2014 03:55:24

and I want to convert it to a 4 byte hexadecimal value. My question is similar to this one: question, but the difference is that I have a different format, and I use the gmtime() function because I want the date since the Epoch. This is what I tried so far (by trying to break the code from the answer of the similar question into smaller parts):

ut = time.strftime("%a, %d %b %Y %H:%M:%S ", time.gmtime())
time.strptime(ut, '%a, %d %b %Y %H:%M:%S')

But I get the error:

ValueError: uncoverted data remains:

Could you please help me? I know that it is a simple question, but I cannot see what is the problem.

Community
  • 1
  • 1
user1956185
  • 389
  • 4
  • 8
  • 16
  • `gmtime()` returns UTC time. Given UTC time, you can get "seconds since Epoch" number but they are **different** things. Are you sure that the input time string (e.g., "Fri, 19 Dec 2014 03:55:24") is in UTC (and not in you local timezone)? – jfs Dec 20 '14 at 09:57

2 Answers2

0

Remove the trailing space in the format string used in

ut = time.strftime("%a, %d %b %Y %H:%M:%S ", time.gmtime())

The line should read:

ut = time.strftime("%a, %d %b %Y %H:%M:%S", time.gmtime())

Without the space after %S, it runs on my side!

jkalden
  • 1,548
  • 4
  • 24
  • 26
0

There are several steps:

  1. Parse rfc 5322 time string into an object that represent the broken-down time

    import email.utils
    time_tuple = email.utils.parsedate("Fri, 19 Dec 2014 03:55:24")
    
  2. Convert the broken-down time into "seconds since Epoch" number

    import calendar
    timestamp = calendar.timegm(time_tuple) # assume input time is in UTC
    
  3. Print the number in hex format

    print('%08X' % timestamp)
    # -> 5493A1AC
    
Community
  • 1
  • 1
jfs
  • 399,953
  • 195
  • 994
  • 1,670