How to Format a Date of Bytes(Pyhon)

Asked

Viewed 23 times

1

Good afternoon I have the following doubt, I would like to print the date as follows for example 5/24/2019 but what this happens is the following

print(date)
Data: b'20290510113138Z'

I have the following code

cert =crypto.load_certificate(crypto.FILETYPE_PEM,open(cert_file).read())
date = cert.get_notAfter()
print("Data:",date)

found a code that solves the problem but do not know how to implement in my code any suggestion?

datetime.strtime(cert.get_notAfter().decode('ascii'), '%Y%m%d%H%M%SZ')
  • the date in bytes of your example is which? 10/5/2029? pq. if it is 24/5/2019, it is very difficult to kill the riddle -

  • the date is 5/10/2029 but can also be 10/5/2029 has no problem

  • hmm.. MAY 10! why if it is OCTOBER 5, it has problem yes, as the most buggered protocol in history. (but the example you set extracts the month in the right order)

  • 1

    in the next question, when placing examples of the data you have, and the desired output, please put the output that would result of those input data, not something completely disconnected. A date-time in bytes could be binary coded, and the conversion process would be completely different, for example.

1 answer

3

import datetime

cert =crypto.load_certificate(crypto.FILETYPE_PEM,open(cert_file).read())
enc_date = cert.get_notAfter().decode("ascii")
date = datetime.strptime(enc_date, '%Y%m%d%H%M%SZ')

print("Data:",date.strftime("%m/%d/%Y"))

Keeping the darta in the American style, with the month before the day, as in your example.

The so-called "strptime" (the p of "parse") and "strftime" ("f" of "format") convert strings into date-time objects and vice versa - the calls exist in the standard operating system library, available in C and Python exposes a version of them in its own standard library.

https://docs.python.org/3/library/datetime.html#strftime-strptime-behavior

  • i had already done something like this but always gave the following error 'str' Object has no attribute 'strftime'

  • 1

    yes - the method name is "strftime", not "strtime" - a typo at some point - in which case you were right to ask.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.