Creating time stamps

Michael F. Stemper michael.stemper at gmail.com
Mon Jul 22 17:25:32 EDT 2019


On 22/07/2019 15.58, Chris Angelico wrote:
> 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.

Cleaned my contacts, cleaned my readers. Still see strftime() in the
third line. Tried to run the code without the second line. It ran
without complaint.

Apparently, the strftime() in that last line is not the one that I
explicitly imported, but a method of datetime.now(). Did I get that
right?


>   I'd go
> with the second one, but with just a single import.

Sounds like a winner to me. Thanks.


-- 
Michael F. Stemper
87.3% of all statistics are made up by the person giving them.



More information about the Python-list mailing list