Adrianopolis Adrianopolis - 1 month ago 10
Python Question

Python How to Check if time is midnight and not display time if true

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.

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)

Answer

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

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)

Note that I've changed format to date_fmt, because format() is already a builtin. Also, from a design standpoint, it's probably not a great idea to have time override the specified format string, so maybe change the "add time" portion to be date_fmt = date_fmt + ' %H:%M'.

Demonstration:

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

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