Python How to Check if time is midnight and not display time if true
<p>I'm modifying our pacific time zone filter to include a time option. I don't want the time component to be shown if midnight. The only import thus far we are using is dateutil.parser. Any pointers on best solution would be appreciated! Thanks.</p>

<pre><code>def to_pacific_date_str(timestamp, format='%Y-%m-%d', time=False):
    pacific_timestamp = timestamp

    if time:
        format='%Y-%m-%d %H:%M' # 2016-10-03 00:00
    if timestamp.tzname() is None:
        # setting timezone lost when pulled from DB
        utc_timestamp = timestamp.replace(tzinfo=pytz.utc)
        # always converting to pacific timezone
        pacific_timestamp = utc_timestamp.astimezone(pytz.timezone('US/Pacific'))
    return pacific_timestamp.strftime(format)
</code></pre>

<p>I believe the best thing to do would be to just take the <code>time()</code> from the <code>datetime</code> before passing it, then compare that to <code>datetime.time(0, 0)</code>.</p>

<pre><code>import pytz
import datetime

def to_pacific_date_str(timestamp, date_fmt='%Y-%m-%d', time=False):
    pacific_timestamp = timestamp

    if timestamp.tzinfo is None:
        # setting timezone lost when pulled from DB
        utc_timestamp = timestamp.replace(tzinfo=pytz.utc)
        # always converting to pacific timezone
        pacific_timestamp = utc_timestamp.astimezone(pytz.timezone('US/Pacific'))

    if time and pacific_timestamp.time() != datetime.time(0, 0):
        date_fmt = '%Y-%m-%d %H:%M' # 2016-10-03 00:00

    return pacific_timestamp.strftime(date_fmt)
</code></pre>

<p>Note that I've changed <code>format</code> to <code>date_fmt</code>, because <a href="https://docs.python.org/3/library/functions.html#format" rel="nofollow"><code>format()</code> is already a builtin</a>. Also, from a design standpoint, it's probably not a great idea to have <code>time</code> override the specified format string, so maybe change the "add time" portion to be <code>date_fmt = date_fmt + ' %H:%M'</code>.</p>

<p>Demonstration:</p>

<pre><code>&gt;&gt;&gt; PST = pytz.timezone('US/Pacific')
&gt;&gt;&gt; to_pacific_date_str(PST.localize(datetime.datetime(2015, 4, 1, 0, 0)), time=True)
'2015-04-01'

&gt;&gt;&gt; PST = pytz.timezone('US/Pacific')
&gt;&gt;&gt; to_pacific_date_str(PST.localize(datetime.datetime(2015, 4, 1, 2, 0)), time=True)
'2015-04-01 02:00'
</code></pre>

python datetime timezone pytz