Convert datetime from PDT to UTC in python - python

I have an object of <class 'datetime.datetime'>.
obj = datetime.datetime(2021, 6, 28, 2, 15, tzinfo=<FixedOffset '-07:00'>)
The time zone is PDT(offset -7:00). I need to convert it to UTC.
So if the object has datetime as 2021-05-02 10:00:00.000 -07:00.
It should be changed to 2021-05-02 17:00:00.000 +00:00.
How to achieve this in python?

Try the following, using .astimezone():
>>> import datetime
>>> obj = datetime.datetime.now()
>>> obj
datetime.datetime(2021, 7, 19, 13, 18, 26, 601212)
>>> obj.astimezone(tz=datetime.timezone.utc)
datetime.datetime(2021, 7, 19, 17, 18, 26, 601212, tzinfo=datetime.timezone.utc)

use time delta
bj = dt.datetime(2021,6,28,10,0)+dt.timedelta(hours=7)
pd.to_datetime(bj)

Related

set datetime object time value to 0

I need to set the time value of detatime objects to 00:00, so I can easily compare two 'dates'
Now I do:
extracted_start_date = datetime.strptime(extracted_start_date.strftime('%Y-%m-%d'), '%Y-%m-%d')
so I have my datetime object
$ datetime.datetime(2021, 3, 18, 11, 13, 53, 782088),
I extract the date string strftime('%Y-%m-%d')
$ '2021-03-18'
and put this back into a datetime object now wch has time 00:00
$ datetime.datetime(2021, 3, 18, 0, 0)
This seems quite elaborate, is there a more efficient way, or is it OK like this?
datetime.datetime objects have method date which return datetime.date instance and these might be used for day-based comparison, consider following example:
import datetime
d1 = datetime.datetime(2021, 3, 17, 9, 0, 0) # yesterday 9:00
d2 = datetime.datetime(2021, 3, 18, 9, 0, 0) # today 9:00
d3 = datetime.datetime(2021, 3, 18, 12, 0, 0) # today 12:00
print(d1.date() == d2.date())
print(d2.date() == d3.date())
output:
False
True
You could use the replace method instead.
from datetime import datetime
d = datetime(2021, 3, 18, 11, 13, 53, 782088)
d.replace(hour=0, minute=0, second=0, microsecond=0)
> datetime.datetime(2021, 3, 18, 0, 0)

Datetime print time without offset

I am currently trying to convert times from UTC and the problem that i am having is that the offsets seem to be backwards. As you can see when i convert the UTC to EST, it shows an offset of -4:56 yet when i print the time, it seems to add 4:56 as opposed to the way it should be. I would really like to be able to convert a UTC time to any other timezone and have it display the local time there without the offset so the UTC here would be converted to something along the lines of 2019-03-06 9:12 EST.
>>> example.created
datetime.datetime(2019, 3, 6, 14, 8, 49, 841881, tzinfo=<UTC>)
>>> original_utc = example.created
>>> original_utc
datetime.datetime(2019, 3, 6, 14, 8, 49, 841881, tzinfo=<UTC>)
>>> conv_est = original_utc.replace(tzinfo=pytz.timezone('US/Eastern'))
>>> conv_est
datetime.datetime(2019, 3, 6, 14, 8, 49, 841881, tzinfo=<DstTzInfo 'US/Eastern' LMT-1 day, 19:04:00 STD>)
>>> print(conv_est)
2019-03-06 14:08:49.841881-04:56
>>> print(conv_est.astimezone())
2019-03-06 19:04:49.841881+00:00
I suspect that you misunderstood the method .astimezone().
Your original datetime is in UTC
>>> example.created
datetime.datetime(2019, 3, 6, 14, 8, 49, 841881, tzinfo=<UTC>)
Then you changed the timezone info for the variable conv_est, and indeed it works as designed:
>>> conv_est = original_utc.replace(tzinfo=pytz.timezone('US/Eastern'))
>>> conv_est
datetime.datetime(2019, 3, 6, 14, 8, 49, 841881, tzinfo=<DstTzInfo 'US/Eastern' LMT-1 day, 19:04:00 STD>)
If you print this variable, it shows the correct info
>>> print(conv_est)
2019-03-06 14:08:49.841881-04:56
But when you call .astimezone() without any argument, then the return value is a datetime object in UTC zone; that means the method is also working as designed, returning the same point in time but expressed as localtime in UTC (It will be 7PM/19hs in UTC when it is 2PM/14hs in US/Eastern).
>>> print(conv_est.astimezone())
2019-03-06 19:04:49.841881+00:00
You can test that yourself by calculating the difference (which will be 0):
>>> conv_est == conv_est.astimezone()
True
>>> conv_est - conv_est.astimezone()
datetime.timedelta(0)

Why isn't my code working to make datetime objects timezone-aware?

I have two python datetime objects that represent the same moment in time:
a = datetime.datetime(2018, 10, 28, 13, 26, 30)
b = datetime.datetime(2018, 10, 28, 7, 26, 30)
Both are coming from different sources.
I know that the first is in UTC, and the second is in "America/Edmonton" (MDT).
Neither initially have a timezone attached to them.
I need to add timezones to these objects and compare them in a way where a == b is True.
What I did was this:
import datetime
from pytz import timezone
a = datetime.datetime(2018, 10, 28, 13, 26, 30)
b = datetime.datetime(2018, 10, 28, 7, 26, 30)
a = a.replace(tzinfo=timezone("UTC"))
b = b.replace(tzinfo=timezone("America/Edmonton"))
a = a.astimezone(timezone("America/Edmonton"))
b = b.astimezone(timezone("America/Edmonton"))
print(repr(a))
# Result: datetime.datetime(2018, 10, 28, 7, 26, 30, tzinfo=<DstTzInfo 'America/Edmonton' MDT-1 day, 18:00:00 DST>)
print(repr(b))
# Result: datetime.datetime(2018, 10, 28, 7, 26, 30, tzinfo=<DstTzInfo 'America/Edmonton' LMT-1 day, 16:26:00 STD>)
a == b # Results in False for some reason
What is "MDT-1 day, 18:00:00 DST" vs "LMT-1 day, 16:26:00 STD"? Why are they different? What am I doing wrong?
The proper way to do this appears to be:
import datetime
from pytz import timezone
a = datetime.datetime(2018, 10, 28, 13, 26, 30)
b = datetime.datetime(2018, 10, 28, 7, 26, 30)
a = timezone('UTC').localize(a)
b = timezone('America/Edmonton').localize(b)
a == b
As demonstrated here. This does result in a being equal to b. Still not sure why it sounds like pytz is defaulting to using a system from before 1893.

Daylight time saving aware conversion of timestamps in python

Given a timestamp without time zone (e.g. 2018-03-12 09:30:00) AND the timezone EST5EDT, the goal is to parse the data returning a datetime object that is time zone AND daylight saving aware.
from datetime import datetime
import pytz
datetime(2018, 3, 8, 9, 30, tzinfo=pytz.timezone('EST5EDT')).astimezone(pytz.utc)
# returns:
# datetime.datetime(2018, 3, 8, 14, 30, tzinfo=<UTC>)
datetime(2018, 3, 12, 9, 30, tzinfo=pytz.timezone('EST5EDT')).astimezone(pytz.utc)
# returns:
# datetime.datetime(2018, 3, 12, 14, 30, tzinfo=<UTC>)
# BUT should return (second Sunday of march the daylight saving changes by 1 hour):
# datetime.datetime(2018, 3, 12, 13, 30, tzinfo=<UTC>)
Never set tzinfo directly when creating datetimes. Always use the localize() method of the timezone (see the note at the top of http://pytz.sourceforge.net/):
pytz.timezone('EST5EDT').localize(
datetime(2018, 3, 12, 9, 30)
).astimezone(pytz.utc)

Convert list of datetime.datetime variables

I have a list of variable that includes several datetime.datetime type variables.
I.e.:
a['PrTimeStamp'] # Type list
[0] datetime.datetime(2014, 10, 19, 10, 0) # Type datetime
[1] datetime.datetime(2014, 12, 3, 12, 0) # Type datetime
[2] datetime.datetime(2014, 12, 4, 0, 0) # Type datetime
[3] datetime.datetime(2014, 12, 10, 13, 0) # Type datetime
[4] datetime.datetime(2014, 12, 16, 20, 0) # Type datetime
[5] datetime.datetime(2014, 12, 17, 2, 0) # Type datetime
E.g. if I make print(a['PrTimeStamp'][0]) it prints to screen: 2014-10-19 10:00:00.
Now I want to convert this list to a format that can be easily read by matlab.
I tried to do the following:
a['PrTimeStamp'] = a['PrTimeStamp'].strftime("%d-%b-%Y %H:%M:%S"))
But I got an error:
AttributeError: 'list' object has no attribute 'strftime'
date[]
for i in a['PrTimeStamp']:
date.append(i.strftime("%d-%b-%Y %H:%M:%S"))
a must be a dictionary has a key PrTimeStamp
I'm pretty sure you need data.strftime to format the dates. Something similar to this.
How to change time formats in python?
Since a['PrTimeStamp'] is a list of date time objects, you need to iterate each item in the list and format the date time object in it!
Since you haven't posted the entire code,
a={}
import datetime
a['PrTimeStamp'] = [ datetime.datetime(2014, 10, 19, 10, 0)
, datetime.datetime(2014, 12, 3, 12, 0)
, datetime.datetime(2014, 12, 4, 0, 0)
, datetime.datetime(2014, 12, 10, 13, 0)
, datetime.datetime(2014, 12, 16, 20, 0)
, datetime.datetime(2014, 12, 17, 2, 0)]
#this is what you need!
print [ts.strftime("%d-%b-%Y %H:%M:%S") for ts in a['PrTimeStamp']]
will print
['19-Oct-2014 10:00:00', '03-Dec-2014 12:00:00', '04-Dec-2014 00:00:00', '10-Dec-2014 13:00:00', '16-Dec-2014 20:00:00', '17-Dec-2014 02:00:00']
Hope it helps!

Categories