How to convert UTC-4 to US/Eastern in python? - python

I read time stamps from text file. These time stamps are in UTC-4. I need to convert them to US/Eastern.
import datetime
datetime_utc4 = datetime.datetime.strptime("12/31/2012 16:15", "%m/%d/%Y %H:%M")
How do I convert it to US/Eastern? One-line answer would be best.
Note: my original question stated EST to EDT. But it does not change the essence of the question, which is how to go from one time zone to another. Upon some reading (following comments) I gather that python (pytz in particular) does not treat EST and EDT as separate time zones, rather as two flavors of US/Eastern. But this is an implementation detail. It is common to refer to EST and EDT as two different time zones, see e.g. here.

Based on your update and comments, I now understand that you have data that is fixed at UTC-4 and you want to correct this so that it is valid in US Eastern Time, including both EST/EDT where appropriate. Here is how you do that with pytz.
from datetime import datetime
import pytz
dt = datetime.strptime("12/31/2012 16:15", "%m/%d/%Y %H:%M") \
.replace(tzinfo = pytz.FixedOffset(-240)) \
.astimezone(pytz.timezone('America/New_York'))
Note that I used the America/New_York time zone id. This is the most correct form of identifier. You could instead use US/Eastern and it would work just fine, but be aware that this is an alias, and it is just there for backwards compatibility.

Related

Convert an RFC 3339 nano time to Python datetime

Is there an easy way to convert an RFC 3339 nano time into a regular Python timestamp?
For example, time = '2022-07-14T12:01:25.225089838+08:00',
I found a way using datetime
from datetime import datetime
time = '2022-07-14T12:01:25.225089+08:00'
date = datetime.fromisoformat(time) # good
time = '2022-07-14T12:01:25.225089838+08:00'
date = datetime.fromisoformat(time) # error
It works with string like '2022-07-14T12:01:25.225089+08:00', but it doesn't work with the time above.
There are a few ways to do it.
Depends on what is the input format and how you define an easy way.
There are actually many post asking similar issues you have.
I'll post a few at the end for your reference if you are interested and please check next time before posting.
The main issue of datetime object is that it only holds 6 digit after second.
You will need a different data structure to save it if you want to preserve all of the digits.
If you are ok with cutting off at 6 digit, FObersteiner's answer is perfect.
Another methodology is vanilla datetime string parsing
from datetime import datetime
date = '2022-07-14T12:01:25.225089838+08:00'.removesuffix('+08:00')
x = datetime.strptime( date[:-3], '%Y-%m-%dT%H:%M:%S.%f')
If you would like to preserve all the digits. You may want to create your own class extending from the datetime class or create some function for it.
Convert an RFC 3339 time to a standard Python timestamp
Parsing datetime strings containing nanoseconds
from datetime.fromisoformat docs:
Caution: This does not support parsing arbitrary ISO 8601 strings - it is only intended as the inverse operation of datetime.isoformat(). A more full-featured ISO 8601 parser, dateutil.parser.isoparse is available in the third-party package dateutil.
dateutil's isoparse will do the job:
from dateutil.parser import isoparse
time = '2022-07-14T12:01:25.225089838+08:00'
date = isoparse(time)
print(date)
# 2022-07-14 12:01:25.225089+08:00
print(repr(date))
# datetime.datetime(2022, 7, 14, 12, 1, 25, 225089, tzinfo=tzoffset(None, 28800))
Note: it doesn't round to microseconds, it just slices off the last 3 decimal places. So basically, if you're dealing with a standardized format like RFC 3339, you can do the slicing yourself like
from datetime import datetime
time = '2022-07-14T12:01:25.225089838+08:00'
date = datetime.fromisoformat(time[:-9] + time[-6:])
print(date)
# 2022-07-14 12:01:25.225089+08:00

How to format a datetime string as defined below?

How can I format a datetime string like 2020-04-30T22:30:00-04:00 to something like 2015-03-22T10:00:00+0900 in Python? The formatting, not the actual date.
The 2 examples you have provided don't appear to have different formatting,
they're both ISO8601 Extended format.
If you need to specify your own format you can use the datetime function strftime and a format string, the reverse of this is strptime, which takes an input string and a format string and returns a datetime object
If you need to change timezones then the tzinfo object what your looking for
You might also be interested in the dateutil
Computing of relative deltas (next month, next year, next Monday, last week of month, etc);
Computing of relative deltas between two given date and/or datetime objects;
Computing of dates based on very flexible recurrence rules, using a superset of the iCalendar specification.
Parsing of RFC strings is supported as well. Generic parsing of dates in almost any string format
Timezone (tzinfo) implementations for tzfile(5) format files (/etc/localtime,/usr/share/zoneinfo, etc), TZ environment string (in all known
formats), iCalendar format files, given ranges (with help from relative deltas), local machine timezone, fixed offset timezone, UTC timezone, and Windows registry-based time zones. Internal up-to-date world timezone information based on Olson’s database.
Computing of Easter Sunday dates for any given year, using Western, Orthodox or Julian algorithms

timezone aware vs. timezone naive in python

I am working with datetime objects in python. I have a function that takes a time and finds the different between that time and now.
def function(past_time):
now = datetime.now()
diff = now - past_time
When I initialized past_time before passing it to this function I initialized it as datetime naive. And now is also a datetime naive object. However when I try to call this function I get the error: can't subtract offset-naive and offset-aware datetimes. How come this is the case if they are both theoretically datetime naive objects?
Any help would be appreciated. Thanks!
datetime doesn't do any cross time zone calculations, because it's a complex and involved subject.
I suggest converting dates to UTC universally and performing maths on those.
I recently completed a project using timezones in a large python/Django project and after investigation went with converting everything internally to UTC and converting only on display to the user.
You should look into pytz to do the conversions to/from UTC, and store Olson codes for the timezones you want in your app - perhaps associated with each user, or appropriate to your program.
Use :
now = now.replace(tzinfo=past_time.tzinfo)
before diff = now - past_time.
so that both now and past_time have same tzinfo.
only if now and past_time intended to be in same timezone.

Difference between Python datetime vs time modules

I am trying to figure out the differences between the datetime and time modules, and what each should be used for.
I know that datetime provides both dates and time. What is the use of the time module?
Examples would be appreciated and differences concerning timezones would especially be of interest.
The time module is principally for working with Unix time stamps; expressed as a floating point number taken to be seconds since the Unix epoch. the datetime module can support many of the same operations, but provides a more object oriented set of types, and also has some limited support for time zones.
Stick to time to prevent DST ambiguity.
Use exclusively the system time module instead of the datetime module to prevent ambiguity issues with daylight savings time (DST).
Conversion to any time format, including local time, is pretty easy:
import time
t = time.time()
time.strftime('%Y-%m-%d %H:%M %Z', time.localtime(t))
'2019-05-27 12:03 CEST'
time.strftime('%Y-%m-%d %H:%M %Z', time.gmtime(t))
'2019-05-27 10:03 GMT'
time.time() is a floating point number representing the time in seconds since the system epoch. time.time() is ideal for unambiguous time stamping.
If the system additionally runs the network time protocol (NTP) dæmon, one ends up with a pretty solid time base.
Here is the documentation of the time module.
The time module can be used when you just need the time of a particular record - like lets say you have a seperate table/file for the transactions for each day, then you would just need the time.
However the time datatype is usually used to store the time difference between 2 points of time.
This can also be done using datetime, but if we are only dealing with time for a particular day, then time module can be used.
Datetime is used to store a particular data and time for a record. Like in a rental agency. The due date would be a datetime datatype.
Just noticed that time is more precise than datetime with an extra digit.
import time as tm
from datetime import datetime as dt
restime = tm.time()
resdtime = dt.timestamp(dt.now())
print("TIME:".rjust(10," "),restime)
print("DATETIME:".rjust(10," "),resdtime)
Output
TIME: 1637357103.7650678
DATETIME: 1637357103.765067

How do I find difference between times in different timezones in Python?

I am trying to calculate difference(in seconds) between two date/times formatted as following:
2010-05-11 17:07:33 UTC
2010-05-11 17:07:33 EDT
time1 = '2010-05-11 17:07:33 UTC'
time2 = '2010-05-11 17:07:33 EDT'
delta = time.mktime(time.strptime(time1,"%Y-%m-%d %H:%M:%S %Z"))-\
time.mktime(time.strptime(time2, "%Y-%m-%d %H:%M:%S %Z"))
The problem I got is EDT is not recognized, the specific error is
ValueError: time data '2010-05-11 17:07:33 EDT' does not match format '%Y-%m-%d %H:%M:%S %Z'
Check out the pytz world timezone definitions library.
This library allows accurate and cross platform timezone calculations using Python 2.3 or higher. It also solves the issue of ambiguous times at the end of daylight savings, which you can read more about in the Python Library Reference (datetime.tzinfo).
It takes advantage of the tz database, which should include EDT, and allow you to perform the calculations you need to (and probably more reliably & accurately than your current implementation).
In addition to pytz, check out python-dateutil. The relativedelta functionality is outstanding.
Here's a sample of using them together:
from datetime import datetime
from dateutil.relativedelta import *
import pytz
if __name__ == '__main__':
date_one = datetime.now(pytz.timezone('US/Eastern'))
date_two = datetime.now(pytz.timezone('US/Mountain'))
rdelta = relativedelta(date_one, date_two)
print(rdelta)
From docs for strptime
Support for the %Z directive is based
on the values contained in tzname and
whether daylight is true. Because of
this, it is platform-specific except
for recognizing UTC and GMT which are
always known (and are considered to be
non-daylight savings timezones).

Categories

Resources