Search code examples
pythonpython-3.xdatetimepytz

UTC representation of midnight on the UTC day that was in progress 24 hours ago in python


I want to format timestamp to day -1 but require a format I am getting day-1 exactly minus 24 hrs but I need from midnight onwards

from datetime import datetime,timedelta
import pytz
partdate=datetime.today().strftime('%Y-%m-%d %H:%M:%S')
# print(partdate)

# import pytz

tzinfo=pytz.timezone('US/Eastern')
# print(tzinfo)


x=(datetime.now() + timedelta(days=-1))  # Here
tzinfo=pytz.timezone('US/Eastern')
pardate1=tzinfo.localize(datetime.now()+timedelta(days=-1),is_dst=None)
print(pardate1)
#print('x----->',x)
#print('timevalue',tzinfo)


# yesterday = datetime.today() - timedelta(days = 1 )
# print(yesterday)

output is 2022-08-13 20:39:26.232974-04:00

But required output is 2022-08-13T00:00:000Z

datetime error


Solution

  • IIUC, you want date/time now in a certain time zone, subtract one day, then convert to UTC, then 'floor' that date/time to midnight.

    Here's a step-by-step example how you can do that. Note that I use zoneinfo since pytz is deprecated and time zone name "America/New_York" as "US/Eastern" is obsolte as well.

    from datetime import datetime, timedelta
    from zoneinfo import ZoneInfo
    
    now = datetime.now(ZoneInfo("America/New_York"))
    
    daybefore = now - timedelta(days=1)
    
    daybefore_UTC = daybefore.astimezone(ZoneInfo("UTC"))
    
    daybefore_UTC_midnight = daybefore_UTC.replace(hour=0, minute=0, second=0, microsecond=0)
    
    print(now)
    print(daybefore_UTC_midnight)
    # 2022-08-15 03:38:42.006215-04:00
    # 2022-08-14 00:00:00+00:00