How to get EST timezone in Python - python

I would like to get the EST time with Python. I have the following code:
import datetime
from pytz import timezone
import time
now_EST = datetime.datetime.today().astimezone(timezone('EST'))
print(now_EST)
And the output is:
2022-03-29 09:52:55.130992-05:00
But when I google the EST time zone, I find out that the time right now is 10:52 am EST, which essentially is the right time.
Why does my code show the 1 hour earlier time compared to the correct one?

use a proper IANA time zone name to avoid ambiguities of the abbreviations.
from datetime import datetime
import pytz
print(datetime.now(pytz.timezone("America/New_York")))
# 2022-03-29 11:20:30.917144-04:00
If you happen to use Python 3.9 or higher, use the built-in zoneinfo module to set the time zone (pytz is deprecated):
from datetime import datetime
from zoneinfo import ZoneInfo
print(datetime.now(ZoneInfo("America/New_York")))
# 2022-03-29 11:20:30.917144-04:00

Daylight Saving Time. Try "EST5EDT"

Related

Converting specific timezone datetime to utc datetime [duplicate]

>>> import pytz
>>> pytz.timezone('Asia/Hong_Kong')
<DstTzInfo 'Asia/Hong_Kong' LMT+7:37:00 STD>
A seven hour and 37 minute offset? This is a little strange, does anyone experience the same issue?
In fact I'm getting different behavior between
import pytz
from datetime import datetime
hk = pytz.timezone('Asia/Hong_Kong')
dt1 = datetime(2012,1,1,tzinfo=hk)
dt2 = hk.localize(datetime(2012,1,1))
if dt1 > dt2:
print "Why?"
Time zones and offsets change over the years. The default zone name and offset delivered when pytz creates a timezone object are the earliest ones available for that zone, and sometimes they can seem kind of strange. When you use localize to attach the zone to a date, the proper zone name and offset are substituted. Simply using the datetime constructor to attach the zone to the date doesn't allow it to adjust properly.
While I'm sure historic changes in timezones are a factor, passing pytz timezone object to the DateTime constructor results in odd behavior even for timezones that have experienced no changes since their inception.
import datetime
import pytz
dt = datetime.datetime(2020, 7, 15, 0, 0, tzinfo= pytz.timezone('US/Eastern'))
produces
2020-07-15 00:00:00-04:56
Creating the datetime object then localizing it produced expected results
import datetime
import pytz
dt = datetime.datetime(2020, 7, 15, 0, 0)
dt_local = timezone('US/Eastern').localize(dt)
produces
2020-07-15 00:00:00-04:00
Coming here nearly 10 years later, I think it's worth a note that we can now exclusively utilize the Python 3.9+ standard library to handle time zones, without a "localize trap".
Use the zoneinfo module to set and replace the tzinfo however you like, ex:
from datetime import datetime
from zoneinfo import ZoneInfo
hk = ZoneInfo('Asia/Hong_Kong')
print(repr(hk))
# zoneinfo.ZoneInfo(key='Asia/Hong_Kong')
dt1 = datetime(2012,1,1,tzinfo=hk)
print(dt1)
# 2012-01-01 00:00:00+08:00
there is a deprecation shim for pytz
Alternatives, if you're not able to use zoneinfo:
for Python < 3.9, there's backports.zoneinfo
you could also use dateutil, which follows the same semantics as zoneinfo
Note for pandas users:
pandas (v1.4.1) is still using pytz internally, and seems to have some trouble with ZoneInfo timezone objects

How to get time in specific timezone in telethon event handler

I am using the telethon library to making telegram bots.
when I using event.date it was printing the time on +00.00 time zone.
How can I print time on specific timezone
See python - Convert UTC datetime string to local datetime. Stealing the top answer which uses python-dateutil:
from dateutil import tz
local_datetime = event.date.astimezone(tz.tzlocal())
from datetime import datetime
print(datetime.now().isoformat(timespec='minutes'))
have a look in datetime library

How to get the UTC offset from a timezone string using pytz?

I am trying to get the UTC offset as a string from my timezone using the Python library pytz.
I am defining it as follows:
import pytz
tz = pytz.timezone('Africa/Cairo')
Now, I want to get '+02:00' from the tz variable, as that is the corresponding UTC offset for Africa/Cairo.
How can I do this? Thanks!
You can use datetime to get current date/time in given timezone and then extract UTC offset,
import pytz
import datetime
tz = pytz.timezone('Africa/Cairo')
print(datetime.datetime.now(tz).utcoffset().total_seconds()/3600)
# output,
2.0

How to search in local time with a Python Script?

I have a script with TwitterSearch using different variables, so that I can convert the retrieved tweets in local time.
However, when I try to add the set_until condition, it begins to search at 8pm instead of midnight (the difference between UTC and my timezone). Can I force it to begin 4 hours later?
Here are the relevant portions of my code :
from time import strftime
from email.utils import parsedate, parsedate_tz, mktime_tz
from datetime import datetime, date
import pytz
The timestamp conversion
timestamp = mktime_tz(parsedate_tz(tweet_time_string))
return datetime.fromtimestamp(timestamp).strftime('%Y-%m-%d %H:%M:%S')
The search criteria
tso.set_until(date(2015,04,18))
Thank you in advance!

What is the easiest way to get current GMT time in Unix timestamp format?

Python provides different packages (datetime, time, calendar) as can be seen here in order to deal with time. I made a big mistake by using the following to get current GMT time time.mktime(datetime.datetime.utcnow().timetuple())
What is a simple way to get current GMT time in Unix timestamp?
I would use time.time() to get a timestamp in seconds since the epoch.
import time
time.time()
Output:
1369550494.884832
For the standard CPython implementation on most platforms this will return a UTC value.
import time
int(time.time())
Output:
1521462189
Does this help?
from datetime import datetime
import calendar
d = datetime.utcnow()
unixtime = calendar.timegm(d.utctimetuple())
print unixtime
How to convert Python UTC datetime object to UNIX timestamp
python2 and python3
it is good to use time module
import time
int(time.time())
1573708436
you can also use datetime module, but when you use strftime('%s'), but strftime convert time to your local time!
python2
from datetime import datetime
datetime.utcnow().strftime('%s')
python3
from datetime import datetime
datetime.utcnow().timestamp()
Python 3 seconds with microsecond decimal resolution:
from datetime import datetime
print(datetime.now().timestamp())
Python 3 integer seconds:
print(int(datetime.now().timestamp()))
WARNING on datetime.utcnow().timestamp()!
datetime.utcnow() is a non-timezone aware object. See reference: https://docs.python.org/3/library/datetime.html#aware-and-naive-objects
For something like 1am UTC:
from datetime import timezone
print(datetime(1970,1,1,1,0,tzinfo=timezone.utc).timestamp())
or
print(datetime.fromisoformat('1970-01-01T01:00:00+00:00').timestamp())
if you remove the tzinfo=timezone.utc or +00:00, you'll get results dependent on your current local time. Ex: 1am on Jan 1st 1970 in your current timezone - which could be legitimate - for example, if you want the timestamp of the instant when you were born, you should use the timezone you were born in. However, the timestamp from datetime.utcnow().timestamp() is neither the current instant in local time nor UTC. For example, I'm in GMT-7:00 right now, and datetime.utcnow().timestamp() gives a timestamp from 7 hours in the future!
Or just simply using the datetime standard module
In [2]: from datetime import timezone, datetime
...: int(datetime.now(tz=timezone.utc).timestamp() * 1000)
...:
Out[2]: 1514901741720
You can truncate or multiply depending on the resolution you want. This example is outputting millis.
If you want a proper Unix timestamp (in seconds) remove the * 1000
At least in python3, this works:
>>> datetime.strftime(datetime.utcnow(), "%s")
'1587503279'
I like this method:
import datetime, time
dts = datetime.datetime.utcnow()
epochtime = round(time.mktime(dts.timetuple()) + dts.microsecond/1e6)
The other methods posted here are either not guaranteed to give you UTC on all platforms or only report whole seconds. If you want full resolution, this works, to the micro-second.
from datetime import datetime as dt
dt.utcnow().strftime("%s")
Output:
1544524990
#First Example:
from datetime import datetime, timezone
timstamp1 =int(datetime.now(tz=timezone.utc).timestamp() * 1000)
print(timstamp1)
Output: 1572878043380
#second example:
import time
timstamp2 =int(time.time())
print(timstamp2)
Output: 1572878043
Here, we can see the first example gives more accurate time than second one.
Here I am using the first one.

Categories