python: Why it tzinfo of datetime.now() none? [duplicate] - python

This question already has answers here:
How do I get a value of datetime.today() in Python that is "timezone aware"?
(19 answers)
Closed 4 years ago.
My timezone is not UTC. When I get the date time with datetime.now() I get the local time, but the tzinfo field has the value none.
I see the same result with python 2.7 and python 3.6.7.
I would expect to get a timezone info or a time offset value. Why is that ? Is there a way to get the time offset as needed for the ISO time format ? 

This is because now will get the present time of any particular timezone, by default it will give you the datetime object of current timezone that you're in (or your computer is set to).
You can get the present time of any other timezone, by passing that timezone to now function.
In [1]: from datetime import datetime
In [2]: import pytz # 3rd party: $ pip install pytz
In [4]: datetime.now()
Out[4]: datetime.datetime(2019, 2, 12, 20, 10, 2, 778532)
In [5]: datetime.now(pytz.utc)
Out[5]: datetime.datetime(2019, 2, 12, 14, 40, 4, 334078, tzinfo=<UTC>)

Related

Calculate hours difference between timezone and UTC based timezone name in following format: America/New_York

I have a library which returns the timezone of a location in the format: America/New_York. Based on that timezone name, I want to calculate the hours between that time zone and UTC, taking into account daylight savings time and all. I'm using Python.
My first idea was to use the Google python library and search for 'America/New_York time' but that only gave me back a list of urls which I could visit to get the info myself. It would be awesome if I could get the current time seen if I were to manually search 'America/New_York time' into google, right into my program.
I'm sure this question has been asked before, but I am new to stack overflow and python so help is appreciated.
Thanks!
The offset from UTC depends on the date (since daylight saving time may or may not be in effect). So you need to provide a datetime for the comparison.
ZoneInfo.utcoffset will return a timedelta object directly.
>>> from zoneinfo import ZoneInfo
>>> from datetime import datetime
>>> ZoneInfo("America/New_York").utcoffset(datetime(2021, 10, 23)) #EDT
datetime.timedelta(days=-1, seconds=72000)
>>> ZoneInfo("America/New_York").utcoffset(datetime(2021, 11, 15)) #EST
datetime.timedelta(days=-1, seconds=68400)
>>> ZoneInfo("Asia/Tokyo").utcoffset(datetime(2021, 10, 23))
datetime.timedelta(seconds=32400)
Not a complete answer, but maybe you could implement a dictionary that connects these format to the normal format with three letters. With this you can then use datetime and pytz to make the rest. If you don't have too many possible outputs in the current format this would be feasible, otherwise of course not.
>>> from datetime import datetime, timedelta
>>> from datetime import timezone
>>> from zoneinfo import ZoneInfo
>>> dt1 = datetime(2020, 11, 1, 8, tzinfo=timezone.utc)
>>> dt2 = datetime(2020, 11, 1, 8, tzinfo=ZoneInfo("America/New_York"))
>>> dt2 - dt1
datetime.timedelta(seconds=18000)
>>>
Note that the difference will be four for five hours depending on whether daylight saving time is in effect or not.

How can I force pytz to use currently standard timezones? [duplicate]

This question already has answers here:
Weird timezone issue with pytz
(3 answers)
Python datetime object show wrong timezone offset
(2 answers)
Closed 13 days ago.
Consider the following:
from datetime import datetime
import pytz
new_years_in_new_york = datetime(
year=2020,
month=1,
day=1,
hour=0,
minute=0,
tzinfo = pytz.timezone('US/Eastern'))
I now I have a datetime object representing January 1, midnight, in New York. Oddly, if I use pytz to convert this to UTC, I'll get an odd datetime off by several minutes:
new_years_in_new_york.astimezone(pytz.utc)
# datetime.datetime(2020, 1, 1, 4, 56, tzinfo=<UTC>)
Notice that midnight in New York, in pytz, is 4:56 in UTC. Elsewhere on Stack Overflow, I learned that's because pytz uses your /usr/share/zoneinfo data, which uses local mean time to account for timezones before standardization. This can be shown here:
pytz.timezone('US/Eastern')
# <DstTzInfo 'US/Eastern' LMT-1 day, 19:04:00 STD>
See that LMK-1 day, 19:04:00 STD? That's a local mean time offset, not the offset I want, which is US/Eastern not during daylight savings time.
Is there a way I can force pytz to use what is currently the standard set of offsets based on a current date? On New Years 2020, it should just be UTC-5. If the date I supplied were during daylight savings time, I would want UTC-4. I'm confused as to why pytz would use a LMT-based offset for a 2020 date.
>>> new_years_in_new_york
datetime.datetime(2020, 1, 1, 0, 0, tzinfo=<DstTzInfo 'US/Eastern' LMT-1 day, 19:04:00 STD>)
Notice the odd offset in that datetime. You're not creating this datetime correctly.
This library only supports two ways of building a localized time. The
first is to use the localize() method provided by the pytz library.
This is used to localize a naive datetime (datetime with no timezone
information):
>>> loc_dt = eastern.localize(datetime(2002, 10, 27, 6, 0, 0))
>>> print(loc_dt.strftime(fmt))
2002-10-27 06:00:00 EST-0500
The second way of building a localized time is by converting an
existing localized time using the standard astimezone() method:
>>> ams_dt = loc_dt.astimezone(amsterdam)
>>> ams_dt.strftime(fmt)
'2002-10-27 12:00:00 CET+0100'
Unfortunately using the tzinfo argument of the standard datetime
constructors ‘’does not work’’ with pytz for many timezones.
>>> datetime(2002, 10, 27, 12, 0, 0, tzinfo=amsterdam).strftime(fmt)
'2002-10-27 12:00:00 LMT+0020'
http://pytz.sourceforge.net/#localized-times-and-date-arithmetic

Subtract 3 months from datetime.now() [duplicate]

This question already has answers here:
How do I calculate the date six months from the current date using the datetime Python module?
(47 answers)
Closed 3 years ago.
How do I remove 3 months from the date? tried to use relativedelta, but I don't have the lib, so is there another way?
from datetime import datetime
now = datetime.now()
print("timestamp =", now)
You can use:
import datetime
a = datetime.datetime.now()
b = a - datetime.timedelta(weeks=12)
Note that you cannot give months as inputs, but weeks and days, and smaller
Perhaps, subtracting with datetime.timedelta can help you estimate the date:
import datetime
datetime.datetime(2019,5,31) - datetime.timedelta(3*365.25/12)
This result is not completely accurate, as it does not account for the leap years in the usual way, however for less precise calculations within a year should suffice. If you need accuracy you will need to use the method below.
For dateutil.relativedelta, you need to first install the module with pip install python-dateutil, and then use it in the following way:
import datetime
from dateutil.relativedelta import relativedelta
datetime.datetime(2019,5,31) - relativedelta(months=3)
If you want to perform complex operations on datetime objects, I can only recommend you to use the library arrow that will handle all the edge cases for you.
The documentation of this library is available here: https://arrow.readthedocs.io/en/latest/
For instance in your case:
>>> import arrow
>>> a = arrow.utcnow()
>>> a
<Arrow [2019-11-20T13:03:52.518238+00:00]>
>>> a.datetime
datetime.datetime(2019, 11, 20, 13, 3, 52, 518238, tzinfo=tzutc())
>>> b = a.shift(months=-3)
>>> b
<Arrow [2019-08-20T13:03:52.518238+00:00]>
>>> b.datetime
datetime.datetime(2019, 8, 20, 13, 3, 52, 518238, tzinfo=tzutc())

How to remove seconds from Python datetime object? [duplicate]

This question already has answers here:
How to truncate the time on a datetime object?
(18 answers)
How to display locale sensitive time format without seconds in python
(4 answers)
Closed 4 years ago.
I have a python datetime object that I want to display on a website, however the time shows in the format hh:mm:ss and I want to display it in the format hh:mm.
I have tried using the replace method as per the following:
message.timestamp.replace(second='0', microsecond=0)
However this doesn't get red of the seconds it just replaces it with hh:mm:00
Use strftime() function
>>> from datetime import datetime
>>> datetime.now()
datetime.datetime(2018, 12, 27, 11, 14, 37, 137010)
>>> now = datetime.now()
>>> now.strftime("%H:%M")
'11:15'

Time conversion using pytz isn't accurate [duplicate]

This question already has answers here:
Python datetime object show wrong timezone offset
(2 answers)
Closed 8 years ago.
I am using the '2014.2' version of pytz. I am converting Asia/Kuwait timezone i.e local time to UTC time using the following process:
>>> from_date = "2014/05/06 17:07"
>>> from_date = dateutil.parser.parse(from_date)
>>> utc=timezone('UTC')
>>> from_date = from_date.replace(tzinfo=timezone('Asia/Kuwait')).astimezone(utc)
>>> from_date
datetime.datetime(2014, 5, 6, 13, 55, tzinfo=<UTC>)
>>> from_date.strftime("%b %d %Y %H:%M:%S" )
'May 06 2014 13:55:00'
The actual UTC time was May 06 2014 14:06:00 which I found in: http://www.worldtimeserver.com/current_time_in_UTC.aspx Why pytz is not exactly converting to the actual time. As you can see there is a time difference between 10-11 minutes.
Don't use datetime.replace() with pytz timezones. From the pytz documentation:
Unfortunately using the tzinfo argument of the standard datetime constructors ‘’does not work’’ with pytz for many timezones.
The reason it doesn't work is that pytz timezones include historical data and datetime is not equipped to handle these.
Use the dedicated timezone.localize() method instead:
>>> import dateutil.parser
>>> from pytz import timezone
>>> from_date = "2014/05/06 17:07"
>>> from_date = dateutil.parser.parse(from_date)
>>> from_date = timezone('Asia/Kuwait').localize(from_date).astimezone(timezone('UTC'))
>>> from_date
datetime.datetime(2014, 5, 6, 14, 7, tzinfo=<UTC>)
>>> from_date.strftime("%b %d %Y %H:%M:%S" )
'May 06 2014 14:07:00'
The timezone.localize() method applies a timezone to a naive datetime object correctly.

Categories

Resources