Time Date Conversion?

Cameron Simpson cs at cskk.id.au
Wed Nov 4 20:01:37 EST 2020


On 04Nov2020 18:02, Steve <Gronicus at SGA.Ninja> wrote:
>The text File entry is:
>   BPd 2020-11-04 17:28:03.352027  66
>
>I bring it into the program using:
>with open("_TIME-DATE.txt" , 'r') as infile:
>     for lineEQN in infile: # loop to find each line in the file for that
>dose
>and set it in a variable as follows:
>ItemDateTime = lineEQN[7:36].strip()
>
>When I print ItemDateTime, it looks like:
>      2020-11-04 17:28:03.352027
>
>How do I display it as "Wednesday, November 4, 2020 5:28pm" ?

Larry has pointed you at strptime and strftime, which read ("parse") a 
string for date information and write ("format") a string for 
presentation. The intermediate form is usually either a timestamp (an 
offset from some point in time, in seconds) or a datetime object (see 
the datetime module).

I'd also point out that your source format looks like a nice ISO8601 
format time, and the datetime module has a handy fromisoformat function 
to the basic forms of that.

As programmers we like the ISO8601 presentation because it has the most 
significant values first and also naively sorts lexically into the time 
ordering.

A less fragile way to parse your example line is to use split() to break 
it into whitepsace separated fields and then parse field[1]+" "+field[2].

That also gets you the first word as field[0], which  might be useful - 
it likely helps classify the input lines in some way.

Cheers,
Cameron Simpson <cs at cskk.id.au>


More information about the Python-list mailing list