How can I change a timezone in a datetimefield.
right now I have
datetime.datetime(2013, 7, 16, 4, 30, tzinfo=<UTC>)
how can modify the tzinfo just for display not to update on the db.
Use pytz for such things.
From the pytz docs, you can use astimezone() to transform time into different time zone, as example below.
>>> eastern = timezone('US/Eastern')
>>> utc_dt = datetime(2002, 10, 27, 6, 0, 0, tzinfo=utc)
>>> loc_dt = utc_dt.astimezone(eastern)
>>> loc_dt.strftime(fmt)
'2002-10-27 01:00:00 EST-0500'
Related
When I run the following code;
tz_Pacific = pytz.timezone('US/Pacific')
tz_Tasmania = pytz.timezone('Australia/Tasmania')
time1 = datetime(2020, 10, 7, 18, 0, 0, tzinfo=tz_Pacific)
time2 = datetime(2020, 10, 7, 14, 20, 21, tzinfo=tz_Tasmania)
print(time1)
print(time2)
I get the following output;
2020-10-07 18:00:00-07:53
2020-10-07 14:20:21+09:49
Why would the tz offsets be -07:53 and +09:49 respectively?
Why you get these "weired" offsets with pytz? Those are the first entries from the database for the respective time zones. With pytz, if you don't localize, these won't be adjusted to the time of your datetime object. Here's a nice blog post by Paul Ganssle giving more insights.
from datetime import datetime
import pytz
tz_Pacific = pytz.timezone('US/Pacific')
tz_Tasmania = pytz.timezone('Australia/Tasmania')
# note the LMT for local mean time:
print(repr(tz_Pacific))
print(repr(tz_Tasmania))
# <DstTzInfo 'US/Pacific' LMT-1 day, 16:07:00 STD>
# <DstTzInfo 'Australia/Tasmania' LMT+9:49:00 STD>
# correctly localized you get
time1 = tz_Pacific.localize(datetime(2020, 10, 7, 18, 0, 0))
time2 = tz_Tasmania.localize(datetime(2020, 10, 7, 14, 20, 21))
print(time1)
print(time2)
# 2020-10-07 18:00:00-07:00
# 2020-10-07 14:20:21+11:00
Further remarks:
With Python 3.9+, you have zoneinfo as part of the standard library to do this.
Example: Display the time in a different time zone.
Note that there is a deprecation shim for pytz.
I am trying to convert from GMT to e.g SGT:
For example, the value
0348 GMT should be 11:48 am
1059 GMT should be 6:59 pm
how do i do this?
i have tried:
date="03:48"
curr = (
dt.datetime.strptime(date, "%H:%M")
.astimezone(timezone('Asia/Singapore'))
)
print(curr)
But I am getting OSError: [Errno 22] Invalid argument
Assuming you have a naive datetime object which represents UTC:
from datetime import datetime, timezone
from dateutil import tz
now = datetime.now()
print(repr(now))
>>> datetime.datetime(2020, 7, 28, 8, 5, 42, 553781)
Make sure to set the tzinfo property to UTC using replace:
now_utc_aware = now.replace(tzinfo=timezone.utc)
print(repr(now_utc_aware))
>>> datetime.datetime(2020, 7, 28, 8, 5, 42, 553781, tzinfo=datetime.timezone.utc)
Now you can convert to another timezone using astimezone:
now_sgt = now_utc_aware.astimezone(tz.gettz('Asia/Singapore'))
print(repr(now_sgt))
>>> datetime.datetime(2020, 7, 28, 16, 5, 42, 553781, tzinfo=tzfile('Singapore'))
Sidenote, referring to your other question, if you parse correctly, you already get an aware datetime object:
date = "2020-07-27T16:38:20Z"
dtobj = datetime.fromisoformat(date.replace('Z', '+00:00'))
print(repr(dtobj))
>>> datetime.datetime(2020, 7, 27, 16, 38, 20, tzinfo=datetime.timezone.utc)
I have time = '2020-06-24T13:30:00-04:00'. How can I change it to a dateTime object in UTC time. I would prefer not to use pd.Timestamp(time).tz_convert("UTC").to_pydatetime() because it returns a weird output that would look like this datetime.datetime(2020, 6, 24, 17, 30, tzinfo=<UTC>). As a result, when I check for equality with datetime.datetime(2020, 6, 24, 17, 30), it return False.
Edit:
import datetime
import pytz
time = '2020-06-24T13:30:00-04:00
dt = datetime.datetime(2020, 6, 24, 17, 30)
print("dt: ",dt)
so = datetime.datetime.strptime(time, '%Y-%m-%dT%H:%M:%S%z').astimezone(pytz.utc)
print("so:",so)
print(dt == so)
outputs
dt: 2020-06-24 17:30:00
so: 2020-06-24 17:30:00+00:00
False
How can I get it to properly evaluate to True?
#1 Since your string is ISO 8601 compatible, use fromisoformat() on Python 3.7+:
from datetime import datetime, timezone
s = '2020-06-24T13:30:00-04:00'
dtobj = datetime.fromisoformat(s)
# dtobj
# datetime.datetime(2020, 6, 24, 13, 30, tzinfo=datetime.timezone(datetime.timedelta(days=-1, seconds=72000)))
Note that this will give you a timezone-aware datetime object; the tzinfo property is a UTC offset. You can easily convert that to UTC using astimezone():
dtobj_utc = dtobj.astimezone(timezone.utc)
# dtobj_utc
# datetime.datetime(2020, 6, 24, 17, 30, tzinfo=datetime.timezone.utc)
#2 You can achieve the same with strptime (also Python3.7+ according to this):
dtobj = datetime.strptime(s, '%Y-%m-%dT%H:%M:%S%z')
dtobj_utc = dtobj.astimezone(timezone.utc)
# dtobj_utc
# datetime.datetime(2020, 6, 24, 17, 30, tzinfo=datetime.timezone.utc)
#3 If you want to turn the result into a naive datetime object, i.e. remove the tzinfo property, replace with None:
dtobj_utc_naive = dtobj_utc.replace(tzinfo=None)
# dtobj_utc_naive
# datetime.datetime(2020, 6, 24, 17, 30)
#4 For older Python versions, you should be able to use dateutil's parser:
from dateutil import parser
dtobj = parser.parse(s)
dtobj_utc = dtobj.astimezone(timezone.utc)
dtobj_utc_naive = dtobj_utc.replace(tzinfo=None)
# dtobj_utc_naive
# datetime.datetime(2020, 6, 24, 17, 30)
Alright so my previous answer was sort of wack because I did not understand your issue entirely so I am rewriting it. You problem is that you are constructing a datetime object from a string and it is timezone aware(UTC). However, whenever you make a datetime object in python, dt = datetime.datetime(2020, 6, 24, 17, 30), it is creating it but with no timezone information (which you can check using .tzinfo on it). All you would need to do is make dt timezone aware when you first create it. See below my code snippit.
import datetime
time = '2020-06-24T13:30:00-04:00'
dt = datetime.datetime(2020, 6, 24, 17, 30, tzinfo=datetime.timezone.utc)
print("dt: ",dt.tzinfo)
so = datetime.datetime.strptime(time, '%Y-%m-%dT%H:%M:%S%z')
print("so:",so.tzinfo)
print(dt == so)
Is it possible to apply timezone when parsing ms to datetime?
My parsing is working but it is displaying local time instead of datetime with timezone:
timestamp = datetime.fromtimestamp(float(dt) / 1000.0,
tz=pytz.timezone("America/Sao_Paulo"))
Not sure if it is happening because timezone from my OS.
This just parses the timestamp as the tz you provide (so it assumes dt is a local time). If dt is absolute / UTC and you want to convert it to a local timezone, you need to first parse it it to a UTC datetime then move its timezone:
datetime.fromtimestamp(timestamp, pytz.utc).astimezone(pytz.timezone('America/Sao_Paulo'))
For instance using 1234567890:
>>> datetime.fromtimestamp(ts, pytz.utc)
datetime.datetime(2009, 2, 13, 23, 31, 30, tzinfo=<UTC>)
>>> datetime.fromtimestamp(ts, pytz.utc).astimezone(pytz.timezone('America/Sao_Paulo'))
datetime.datetime(2009, 2, 13, 21, 31, 30, tzinfo=<DstTzInfo 'America/Sao_Paulo' -02-1 day, 22:00:00 DST>)
Also note that for various historical reasons properly using pytz is not as simple as that (e.g.). If you're going to have to deal with timezones a lot, you may want to take a look at pendulum which tries to make timezone manipulations more reliable, and to provide a friendlier API.
Not sure what the problem is, it seems to be working as expected. My local time is 09:02 and with the Sao Paolo timezone it shows as 10:02, which seems correct.
>>> import datetime, time, pytz
>>> tz_1 = pytz.timezone("America/Sao_Paulo")
>>> tz_1
<DstTzInfo 'America/Sao_Paulo' LMT-1 day, 20:54:00 STD>
>>> now = time.time()
>>> now
1554382930.1575696
>>> datetime.datetime.fromtimestamp(now)
datetime.datetime(2019, 4, 4, 9, 2, 10, 157570)
>>> datetime.datetime.fromtimestamp(now, tz=tz_1)
datetime.datetime(2019, 4, 4, 10, 2, 10, 157570, tzinfo=<DstTzInfo 'America/Sao_Paulo' -03-1 day, 21:00:00 STD>)
Could you elaborate on which part is not displaying as you expected?
I have a mongodb time as objectid("5217a543dd99a6d9e0f74702").
How to convert it to epoch time in Python. (UTC timezone and also EST timezone)
ObjectId.generation_time gives you the time the ObjectId was generated, in UTC:
>>> from bson import ObjectId
>>> ObjectId("5217a543dd99a6d9e0f74702").generation_time
datetime.datetime(2013, 8, 23, 18, 9, 7, tzinfo=<bson.tz_util.FixedOffset object at 0x102920c90>)
The documentation is here.
To convert to Eastern Time, install pytz and:
>>> import pytz
>>> ny = pytz.timezone('America/New_York')
>>> gt = ObjectId("5217a543dd99a6d9e0f74702").generation_time
>>> ny.normalize(gt.astimezone(ny))
datetime.datetime(2013, 8, 23, 14, 9, 7, tzinfo=<DstTzInfo 'America/New_York' EDT-1 day, 20:00:00 DST>)
You can use the ObjectId.getTimestamp() method to get the timestamp portion of the objectid as Date.
Once you have the Date object you can call any of the Date methods to get what you want. In the shell, you could just hit TAB to get the list of all methods that are permitted:
> var myid = new ObjectId()
> myid
ObjectId("5331ba8163083f9b26efb5b3")
> var mytime = myid.getTimestamp()
> mytime
ISODate("2014-03-25T17:18:57Z")
> mytime.<TAB>
mytime.constructor mytime.getUTCFullYear(
mytime.getDate( mytime.getUTCHours(
mytime.getDay( mytime.getUTCMilliseconds(
mytime.getFullYear( mytime.getUTCMinutes(
mytime.getHours( mytime.getUTCMonth(
mytime.getMilliseconds( mytime.getUTCSeconds(
mytime.getMinutes( mytime.getYear(
mytime.getMonth( mytime.hasOwnProperty(
mytime.getSeconds( mytime.propertyIsEnumerable(
mytime.getTime( mytime.setDate(
mytime.getTimezoneOffset( mytime.setFullYear(
mytime.getUTCDate( mytime.setHours(
mytime.getUTCDay( mytime.setMilliseconds(
Note: I'm not familiar with Python, but the same concepts would apply