Apply timezone when convert ms to datetime - python

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?

Related

Difference between datetime.combine() and pytz.localize()

I am a bit puzzled by the following behavior. Suppose I use datetime.combine() to construct a timezone-aware object:
>>> date
datetime.date(2018, 10, 17)
>>> time
datetime.time(6, 0)
>>> tz
<DstTzInfo 'Europe/Berlin' LMT+0:53:00 STD>
>>> datetime.combine(date, time, tzinfo=tz)
datetime.datetime(2018, 10, 17, 6, 0, tzinfo=<DstTzInfo 'Europe/Berlin' LMT+0:53:00 STD>)
or I use pytz.localize() to do the same:
>>> tz.localize(datetime.combine(date, time))
datetime.datetime(2018, 10, 17, 6, 0, tzinfo=<DstTzInfo 'Europe/Berlin' CEST+2:00:00 DST>)
Note how the tzinfo’s timezone name and offset have changed. I am unable to find a proper documentation for that behavior. The pytz documentation says
Unfortunately using the tzinfo argument of the standard datetime constructors “does not work” with pytz for many timezones.
So what exactly is going on here? (Somewhat related questions are here or here.)
You just found out (again) that you should never directly add timezone information when creating timezone-aware datetimes. Always use tz.localize().
The problem you are seeing is because datetime.combine doesn't adjust the tzinfo object to the actual datetime. It still assumes the timezone information of the first valid date in this timezone, which was in the late 1800's and happened to be 0:53:00 off from UTC.

What datetime format string is 2017-01-05T14:23:33.986-0500 in Python

I have a string:
t = "2017-01-05T14:23:33.986-0500"
I need to convert it to a Python date.
I used:
t_obj = datetime.strptime(t, '%Y-%m-%dT%H:%M:%S.%f')
I think it is in YYYY-MM-DD with time as HH:MM:SS.sss , but am not able to figure out what -0500 could be...could it be subtracting -5 hrs for UTC?
Any help would be greatly appreciated
%z is what you need it's the timezone offset from UTC, see the docs
%z - UTC offset in the form +HHMM or -HHMM (empty string if the the object
is naive). (empty), +0000, -0400, +1030
In [89]:
t= "2017-01-05T14:23:33.986-0500"
dt.datetime.strptime(t, '%Y-%m-%dT%H:%M:%S.%f%z')
Out[89]:
datetime.datetime(2017, 1, 5, 14, 23, 33, 986000, tzinfo=datetime.timezone(datetime.timedelta(-1, 68400)))
EdChum's answer is definitely correct. However, there is an easier way to go about parsing dates - python-dateutil:
>>> from dateutil.parser import parse
>>> parse("2017-01-05T14:23:33.986-0500")
datetime.datetime(2017, 1, 5, 14, 23, 33, 986000, tzinfo=tzoffset(None, -18000))
The parse() function is very robust and able to handle a wide variety of date formats:
>>> parse("Friday January 6, 2017 11:12 AM")
datetime.datetime(2017, 1, 6, 11, 12)
This is on 3.6.0 with dateutil 2.6.0.

Convert MongoDB time to epoch time - Python

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

How to convert timezone in Django app

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'

Python datetime not including DST when using pytz timezone

If I convert a UTC datetime to swedish format, summertime is included (CEST). However, while creating a datetime with sweden as the timezone, it gets CET instead of CEST. Why is this?
>>> # Modified for readability
>>> import pytz
>>> import datetime
>>> sweden = pytz.timezone('Europe/Stockholm')
>>>
>>> datetime.datetime(2010, 4, 20, 16, 20, tzinfo=pytz.utc).astimezone(sweden)
datetime(2010, 4, 20, 18, 20, tzinfo=<... 'Europe/Stockholm' CEST+2:00:00 DST>)
>>>
>>> datetime.datetime(2010, 4, 20, 18, 20, tzinfo=sweden)
datetime(2010, 4, 20, 18, 20, tzinfo=<... 'Europe/Stockholm' CET+1:00:00 STD>)
>>>
The sweden object specifies the CET time zone by default but contains enough information to know when CEST starts and stop.
In the first example, you create a datetime object and convert it to local time. The sweden object knows that the UTC time you passed occurs during daylight savings time and can convert it appropriately.
In the second example, the datetime constructor always interprets your input as not-daylight-savings-time and returns an appropriate object.
If datetime treated your input as wall-clock time and chose the appropriate daylight-savings setting for you, there would be an ambiguity during the time of year when clocks are set back. On a wall-clock the same hour occurs twice. Hence, datetime forces you to specify which timezone you're using when you create the datetime object.
Timezone abbreviations are not unique. For example "IST" could refer to "Irish Standard Time", "Iranian Standard Time", "Indian Standard Time" or "Isreali Standard Time". You shouldn't rely on parsing that, and instead should use zoneinfo timezones.

Categories

Resources