shaked
shaked

Reputation: 642

Python get time at specify GMT

I am trying to get the current time at a specific GMT ( like +3 -1 etc.). I have a script that runs on a remote server, and he needs to update the current time at another country which I can not find at the time_zone list. I tried

import pytz
pytz.all_timezones

And look for the country and find it in the list; I know the county GMT is +3.

import datetime 
from django.utils.timezone import now

both now function is relevant to me, and I can not find how I find the now function with GMT +3

Upvotes: 0

Views: 345

Answers (1)

Alexandr Tatarinov
Alexandr Tatarinov

Reputation: 4044

One way to obtain localized time is via timezone.localtime

import pytz
from django.utils import timezone

timezone.localtime(timezone=pytz.timezone('Asia/Jerusalem'))

If you already have a datetime object, you can use datetime.astimezone or again, the timezone.localtime

import pytz
from django.utils import timezone

now = timezone.now()

now.astimezone(pytz.timezone('Asia/Jerusalem'))
timezone.localtime(now, pytz.timezone('Asia/Jerusalem'))

If you want to get the local timezone of a machine, you can run the following. However, I believe there is no magic, and the server must be configured appropriately for this to work.

import time
import pytz
from django.utils import timezone

timezone.localtime(timezone=pytz.timezone(time.tzname[0]))

I've tried tn on AWS EC2 which I have access to, and it just has UTC set, so it's still mostly up to you to specify the desired timezone.

Upvotes: 1

Related Questions