Easy way to convert UTC to another timezone in python - python

I'm trying to convert a UNIX time stamp to UTC+9. I've been searching for hours and it's all very confusing what with the different libraries etc
Here's what I've got so far
from datetime import datetime
from pytz import timezone
import datetime
time = 1481079600
utc_time = datetime.datetime.fromtimestamp(time)#.strftime('%Y-%m-%d %H:%M:%S')
print utc_time.strftime(fmt)
tz = timezone('Japan')
print tz.localize(utc_time).strftime(fmt)
This just prints the same time, what am I doing wrong

I am going to shamelessly plug this new datetime library I am obsessed with, Pendulum.
pip install pendulum
import pendulum
t = 1481079600
pendulum.from_timestamp(t).to_datetime_string()
>>> '2016-12-07 03:00:00'
And now to change it to your timezone super quick and easy!
pendulum.from_timestamp(t, 'Asia/Tokyo').to_datetime_string()
>>> '2016-12-07 12:00:00'

Your utc_time datetime is naive - it has no timezone associated with it. localize assigns a timezone to it, it doesn't convert between timezones. The simplest way to do that is probably to construct a timezone-aware datetime:
import pytz
utc_time = datetime.datetime.fromtimestamp(time, pytz.utc)
Then convert to the timezone you want when you're ready to display it:
print utc_time.astimezone(tz).strftime(fmt)

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

Unix timestamp to iso 8601 time format

When I convert unix time 1463288494 to isoformat i get 2016-05-14T22:01:34. How can I get the output including the -07:00. In this format 2016-05-14T22:01:34-07:00
from datetime import datetime
t = int("1463288494")
print(datetime.fromtimestamp(t).isoformat())
You can pass a tzinfo instance representing your timezone offset to fromtimestamp(). The problem then is how to get the tzinfo object. The easiest way is to use the pytz module which provides a tzinfo compatible object:
import pytz
from datetime import datetime
tz = pytz.timezone('America/Los_Angeles')
print(datetime.fromtimestamp(1463288494, tz).isoformat())
#2016-05-14T22:01:34-07:00

pytz - Converting UTC and timezone to local time

I have a datetime in utc time zone, for example:
utc_time = datetime.datetime.utcnow()
And a pytz timezone object:
tz = timezone('America/St_Johns')
What is the proper way to convert utc_time to the given timezone?
I think I got it:
pytz.utc.localize(utc_time, is_dst=None).astimezone(tz)
This line first converts the naive (time zone unaware) utc_time datetime object to a datetime object that contains a timezone (UTC). Then it uses the astimezone function to adjust the time according to the requested time zone.
It's the exact purpose of fromutc function:
tz.fromutc(utc_time)
(astimezone function calls fromutc under the hood, but tries to convert to UTC first, which is unneeded in your case)
I agree with Tzach's answer. Just wanted to include that the is_dst parameter is not required:
pytz.utc.localize(datetime.utcnow()).astimezone(tz)
That code converts the current UTC time to a timezone aware current datetime.
Whereas the code below converts the current UTC time to a timezone aware datetime which is not necessarily current. The timezone is just appended into the UTC time value.
tz.localize(datetime.utcnow())
May I recommend to use arrow? If I understood the question:
>>> import arrow
>>> utc = arrow.utcnow()
>>> utc
<Arrow [2014-08-12T13:01:28.071624+00:00]>
>>> local = utc.to("America/St_Johns")
>>> local
<Arrow [2014-08-12T10:31:28.071624-02:30]>
You can also use
tz.fromutc(utc_time)
Another very easy way:
Because utcnow method returns a naive object, so you have to convert the naive object into aware object. Using replace method you can convert a naive object into aware object. Then you can use the astimezone method to create new datetime object in a different time zone.
from datetime import datetime
import pytz
utc_time = datetime.utcnow()
tz = pytz.timezone('America/St_Johns')
utc_time =utc_time.replace(tzinfo=pytz.UTC) #replace method
st_john_time=utc_time.astimezone(tz) #astimezone method
print(st_john_time)
You can also use the sample below, I use it for similar task
tz = pytz.timezone('America/St_Johns')
time_difference=tz.utcoffset(utc_time).total_seconds() #time difference between UTC and local timezones in 5:30:00 format
utc_time = date + timedelta(0,time_difference)
It works fast and you don't need to import additional libraries.

Facebook timestamp to Python DateTime Object

Facebook returns 'created_time' in this format:
2012-07-23T08:52:04+0000
I want to convert this timestamp to a normal Python DateTime object.
Have you tried dateutil
It's extremely easy to use
import dateutil.parser as dateparser
dateparser.parse('2012-07-23T08:52:04+0000')
dateutil is very helpful to deal with timezone info, and it can handle lots of time formats.
s = "2005-12-06T12:13:14"
from datetime import datetime
from time import strptime
print datetime(*strptime(s, "%Y-%m-%dT%H:%M:%S")[0:6])

How do I get a value of datetime.today() in Python that is "timezone aware"?

I am trying to subtract one date value from the value of datetime.datetime.today() to calculate how long ago something was. But it complains:
TypeError: can't subtract offset-naive and offset-aware datetimes
The return value from datetime.datetime.today() doesn't seem to be "timezone aware", while my other date value is. How do I get a return value from datetime.datetime.today() that is timezone aware?
The ideal solution would be for it to automatically know the timezone.
Right now, it's giving me the time in local time, which happens to be PST, i.e. UTC - 8 hours. Worst case, is there a way I can manually enter a timezone value into the datetime object returned by datetime.datetime.today() and set it to UTC-8?
In the standard library, there is no cross-platform way to create aware timezones without creating your own timezone class. (Edit: Python 3.9 introduces zoneinfo in the standard library which does provide this functionality.)
On Windows, there's win32timezone.utcnow(), but that's part of pywin32. I would rather suggest to use the pytz library, which has a constantly updated database of most timezones.
Working with local timezones can be very tricky (see "Further reading" links below), so you may rather want to use UTC throughout your application, especially for arithmetic operations like calculating the difference between two time points.
You can get the current date/time like so:
import pytz
from datetime import datetime
datetime.utcnow().replace(tzinfo=pytz.utc)
Mind that datetime.today() and datetime.now() return the local time, not the UTC time, so applying .replace(tzinfo=pytz.utc) to them would not be correct.
Another nice way to do it is:
datetime.now(pytz.utc)
which is a bit shorter and does the same.
Further reading/watching why to prefer UTC in many cases:
pytz documentation
What Every Developer Should Know About Time – development hints for many real-life use cases
The Problem with Time & Timezones - Computerphile – funny, eye-opening explanation about the complexity of working with timezones (video)
Get the current time, in a specific timezone:
import datetime
import pytz
my_date = datetime.datetime.now(pytz.timezone('US/Pacific'))
Remember to install pytz first.
In Python 3.2+: datetime.timezone.utc:
The standard library makes it much easier to specify UTC as the time zone:
>>> import datetime
>>> datetime.datetime.now(datetime.timezone.utc)
datetime.datetime(2020, 11, 27, 14, 34, 34, 74823, tzinfo=datetime.timezone.utc)
You can also get a datetime that includes the local time offset using astimezone:
>>> datetime.datetime.now(datetime.timezone.utc).astimezone()
datetime.datetime(2020, 11, 27, 15, 34, 34, 74823, tzinfo=datetime.timezone(datetime.timedelta(seconds=3600), 'CET'))
(In Python 3.6+, you can shorten the last line to: datetime.datetime.now().astimezone())
If you want a solution that uses only the standard library and that works in both Python 2 and Python 3, see jfs' answer.
In Python 3.9+: zoneinfo to use the IANA time zone database:
In Python 3.9, you can specify particular time zones using the standard library, using zoneinfo, like this:
>>> from zoneinfo import ZoneInfo
>>> datetime.datetime.now(ZoneInfo("America/Los_Angeles"))
datetime.datetime(2020, 11, 27, 6, 34, 34, 74823, tzinfo=zoneinfo.ZoneInfo(key='America/Los_Angeles'))
zoneinfo gets its database of time zones from the operating system, or from the first-party PyPI package tzdata if available.
A one-liner using only the standard library works starting with Python 3.3. You can get a local timezone aware datetime object using astimezone (as suggested by johnchen902):
from datetime import datetime, timezone
aware_local_now = datetime.now(timezone.utc).astimezone()
print(aware_local_now)
# 2020-03-03 09:51:38.570162+01:00
print(repr(aware_local_now))
# datetime.datetime(2020, 3, 3, 9, 51, 38, 570162, tzinfo=datetime.timezone(datetime.timedelta(0, 3600), 'CET'))
Here's a stdlib solution that works on both Python 2 and 3:
from datetime import datetime
now = datetime.now(utc) # Timezone-aware datetime.utcnow()
today = datetime(now.year, now.month, now.day, tzinfo=utc) # Midnight
where today is an aware datetime instance representing the beginning of the day (midnight) in UTC and utc is a tzinfo object (example from the documentation):
from datetime import tzinfo, timedelta
ZERO = timedelta(0)
class UTC(tzinfo):
def utcoffset(self, dt):
return ZERO
def tzname(self, dt):
return "UTC"
def dst(self, dt):
return ZERO
utc = UTC()
Related: performance comparison of several ways to get midnight (start of a day) for a given UTC time.
Note: it is more complex, to get midnight for a time zone with a non-fixed UTC offset.
Another method to construct time zone aware datetime object representing current time:
import datetime
import pytz
pytz.utc.localize( datetime.datetime.utcnow() )
You can install pytz from PyPI by running:
$ pipenv install pytz
Use dateutil as described in Python datetime.datetime.now() that is timezone aware:
from dateutil.tz import tzlocal
# Get the current date/time with the timezone.
now = datetime.datetime.now(tzlocal())
If you are using Django, you can set dates non-tz aware (only UTC).
Comment the following line in settings.py:
USE_TZ = True
Here is one way to generate it with the stdlib:
import time
from datetime import datetime
FORMAT='%Y-%m-%dT%H:%M:%S%z'
date=datetime.strptime(time.strftime(FORMAT, time.localtime()),FORMAT)
date will store the local date and the offset from UTC, not the date at UTC timezone, so you can use this solution if you need to identify which timezone the date is generated at. In this example and in my local timezone:
date
datetime.datetime(2017, 8, 1, 12, 15, 44, tzinfo=datetime.timezone(datetime.timedelta(0, 7200)))
date.tzname()
'UTC+02:00'
The key is adding the %z directive to the representation FORMAT, to indicate the UTC offset of the generated time struct. Other representation formats can be consulted in the datetime module docs
If you need the date at the UTC timezone, you can replace time.localtime() with time.gmtime()
date=datetime.strptime(time.strftime(FORMAT, time.gmtime()),FORMAT)
date
datetime.datetime(2017, 8, 1, 10, 23, 51, tzinfo=datetime.timezone.utc)
date.tzname()
'UTC'
Edit
This works only on python3. The z directive is not available on python 2 _strptime.py code
It should be emphasized that since Python 3.6, you only need the standard lib to get a timezone aware datetime object that represents local time (the setting of your OS). Using astimezone()
import datetime
datetime.datetime(2010, 12, 25, 10, 59).astimezone()
# e.g.
# datetime.datetime(2010, 12, 25, 10, 59, tzinfo=datetime.timezone(datetime.timedelta(seconds=3600), 'Mitteleuropäische Zeit'))
datetime.datetime(2010, 12, 25, 12, 59).astimezone().isoformat()
# e.g.
# '2010-12-25T12:59:00+01:00'
# I'm on CET/CEST
(see #johnchen902's comment).
Note there's a small caveat though, don't expect any "DST-awareness" from a timedelta timezone.
pytz is a Python library that allows accurate and cross platform timezone calculations using Python 2.3 or higher.
With the stdlib, this is not possible.
See a similar question on SO.
Here is a solution using a readable timezone and that works with today():
from pytz import timezone
datetime.now(timezone('Europe/Berlin'))
datetime.now(timezone('Europe/Berlin')).today()
You can list all timezones as follows:
import pytz
pytz.all_timezones
pytz.common_timezones # or
Getting a timezone-aware date in utc timezone is enough for date subtraction to work.
But if you want a timezone-aware date in your current time zone, tzlocal is the way to go:
from tzlocal import get_localzone # pip install tzlocal
from datetime import datetime
datetime.now(get_localzone())
PS dateutil has a similar function (dateutil.tz.tzlocal). But inspite of sharing the name it has a completely different code base, which as noted by J.F. Sebastian can give wrong results.
Another alternative, in my mind a better one, is using Pendulum instead of pytz. Consider the following simple code:
>>> import pendulum
>>> dt = pendulum.now().to_iso8601_string()
>>> print (dt)
2018-03-27T13:59:49+03:00
>>>
To install Pendulum and see their documentation, go here. It have tons of options (like simple ISO8601, RFC3339 and many others format support), better performance and tend to yield simpler code.
Especially for non-UTC timezones:
The only timezone that has its own method is timezone.utc, but you can fudge a timezone with any UTC offset if you need to by using timedelta & timezone, and forcing it using .replace.
In [1]: from datetime import datetime, timezone, timedelta
In [2]: def force_timezone(dt, utc_offset=0):
...: return dt.replace(tzinfo=timezone(timedelta(hours=utc_offset)))
...:
In [3]: dt = datetime(2011,8,15,8,15,12,0)
In [4]: str(dt)
Out[4]: '2011-08-15 08:15:12'
In [5]: str(force_timezone(dt, -8))
Out[5]: '2011-08-15 08:15:12-08:00'
Using timezone(timedelta(hours=n)) as the time zone is the real silver bullet here, and it has lots of other useful applications.
Tyler from 'howchoo' made a really great article that helped me get a better idea of the Datetime Objects, link below
Working with Datetime
essentially, I just added the following to the end of both my datetime objects
.replace(tzinfo=pytz.utc)
Example:
import pytz
import datetime from datetime
date = datetime.now().replace(tzinfo=pytz.utc)
If you get current time and date in python then import date and time,pytz package in python after you will get current date and time like as..
from datetime import datetime
import pytz
import time
str(datetime.strftime(datetime.now(pytz.utc),"%Y-%m-%d %H:%M:%S%t"))
Use the timezone as shown below for a timezone-aware date time. The default is UTC:
from django.utils import timezone
today = timezone.now()
try pnp_datetime, all the time been used and returned is with timezone, and will not cause any offset-naive and offset-aware issues.
>>> from pnp_datetime.pnp_datetime import Pnp_Datetime
>>>
>>> Pnp_Datetime.utcnow()
datetime.datetime(2020, 6, 5, 12, 26, 18, 958779, tzinfo=<UTC>)

Categories