How do I get datetime to stop showing seconds?

Eryk Sun eryksun at gmail.com
Fri Oct 16 06:50:13 EDT 2020


On 10/16/20, Steve <Gronicus at sga.ninja> wrote:
> -----Original Message-----
> From: Python-list <python-list-bounces+gronicus=sga.ninja at python.org> On
> Behalf Of Frank Millman
> Sent: Friday, October 16, 2020 4:34 AM
> To: python-list at python.org
> Subject: Re: How do I get datetime to stop showing seconds?
>
> On 2020-10-16 9:42 AM, Steve wrote:
>> d2 =  datetime.datetime.now() #Time Right now
>>
>> Show this: 2020-10-16 02:53
>> and not this: 2020-10-16 02:53:48.585865
>
>  >>>
>  >>> str(d2)
> '2020-10-16 10:29:38.423371'
>  >>>
>  >>> d2.strftime('%Y-%m-%d %H:%M')
> '2020-10-16 10:29'

datetime also supports the __format__ protocol [1]. For example:

    >>> d2 = datetime(2020, 10, 16, 10, 29, 38, 423371)

    >>> format(d2, '%Y-%m-%d %H:%M')
    '2020-10-16 10:29'

    >>> f'{d2:%Y-%m-%d %H:%M}'
    '2020-10-16 10:29'

[1] https://docs.python.org/3/library/datetime.html#datetime.datetime.__format__


More information about the Python-list mailing list