Чтобы установить часовой пояс объекта datetime.now()
в Python, вы можете использовать различные методы. Вот несколько подходов:
Метод 1: использование библиотеки pytz
import pytz
from datetime import datetime
# Get the current time in UTC
now = datetime.now(pytz.utc)
# Convert to a specific timezone
timezone = pytz.timezone('America/New_York')
now = now.astimezone(timezone)
# Print the result
print(now)
Метод 2. Использование библиотеки dateutil
from dateutil import tz
from datetime import datetime
# Get the current time in UTC
now = datetime.now(tz.tzutc())
# Convert to a specific timezone
timezone = tz.gettz('America/New_York')
now = now.astimezone(timezone)
# Print the result
print(now)
Метод 3: использование метода datetime.replace()
from datetime import datetime
import pytz
# Get the current time
now = datetime.now()
# Set the desired timezone
timezone = pytz.timezone('America/New_York')
# Convert the current time to the desired timezone
now = now.replace(tzinfo=timezone)
# Print the result
print(now)
Метод 4. Использование метода datetime.astimezone()
from datetime import datetime
import pytz
# Get the current time in UTC
now = datetime.now(pytz.utc)
# Set the desired timezone
timezone = pytz.timezone('America/New_York')
# Convert the current time to the desired timezone
now = now.astimezone(timezone)
# Print the result
print(now)