Creating time stamps

Chris Angelico rosuav at gmail.com
Mon Jul 22 16:58:16 EDT 2019


On Tue, Jul 23, 2019 at 6:34 AM Michael F. Stemper
<michael.stemper at gmail.com> wrote:
>
> I have some code that generates a time-stamp as follows:
>
>   from datetime import datetime
>   tt = datetime.now()
>   timestamp = "%4d-%02d-%02d %02d:%02d" % \
>     (tt.year, tt.month, tt.day, tt.hour, tt.minute)
>
> I later realized that I could have written it as:
>
>   from datetime import datetime
>   from time import strftime
>   timestamp = datetime.now().strftime( "%Y-%m-%d %H:%M" )
>
> The first seems a little clunky with its accessing of multiple
> attributes, but the second has an additional import. Is there
> any reason to prefer one over the other?
>

What's the second import doing though? You never use strftime. I'd go
with the second one, but with just a single import.

ChrisA



More information about the Python-list mailing list