'How do I set or freeze time in python?
I want to set a fixed time using python different than that seen locally on my system , so that when I used datetime.date.today() I get to see the desired date
Solution 1:[1]
you can use pytz package with datetime, And assign to date time now.
from datetime import datetime
import pytz
# add wanted timezone instead of America/New_York
timeZone_AN = pytz.timezone('America/New_York')
dt_Ny = datetime.now(timeZone_AN)
print("Datetime: ", dt_Ny)
updated according to MrFuppes comment, as pytz will be deprecated you can use zoneinfo. it seems like it will be more useful than pytz.
from zoneinfo import ZoneInfo
timeZone_AN=("America/New_York")
update
If you want to get a fixed datetime then this will help you.
# set your date as year, month, day
desiredTime_ymd = datetime.date(2020, 9,14)
#print to test
print(desiredTime_ymd)
#set sec, min, hour
desiredTime_smh=time(14, 42, 59)
#print to test
print(desiredTime_smh)
#set all at once
#datetime(year, month, day, hour, minute, second, microsecond)
desredTime_all = datetime(2020, 9,14, 14, 42, 59)
#print to test
print(desiredTime_all)
Solution 2:[2]
Add argument tz_offset. See the doc https://pypi.org/project/freezegun/
from freezegun import freeze_time
@freeze_time("2012-01-14 03:21:34", tz_offset=-4)
def test():
assert datetime.datetime.utcnow() == datetime.datetime(2012, 1, 14, 3, 21, 34)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | |
Solution 2 | angelacpd |