I am having the hardest time trying to get the current time in EDT timezone.
print datetime.time(datetime.now()).strftime("%H%M%S")
datetime.now([tz]) has an optional tz argument, but it has to be of type datetime.tzinfo... I have not ben able to figure out how to define a tzinfo object for Eastern timezone... Seems like it should be pretty simple, but I cant figure it out without importing an additional library.
We can convert the datetime from one timezone to another timezone using the datetime. astimezone() method. This method takes the datetime object as a parameter and returns a new datetime of a given timezone. Let's understand the following example.
A time zone offset of "+hh:mm" indicates that the date/time uses a local time zone which is "hh" hours and "mm" minutes ahead of UTC. A time zone offset of "-hh:mm" indicates that the date/time uses a local time zone which is "hh" hours and "mm" minutes behind UTC.
python is usually used on the server. Local time zone on a server is usually pointless and should always be set to UTC. Setting datetime tzinfo this way fails in some cases. better use UTC, then localize to the wanted timezone only on output.
Timezone aware object using datetime now(). time() function of datetime module. Then we will replace the value of the timezone in the tzinfo class of the object using the replace() function. After that convert the date value into ISO 8601 format using the isoformat() method.
I am not very conversent about the EDT time zone but this example should serve your purpose.
import datetime
datetime.datetime.now must be passed the time zone info which should be of type datetime.tzinfo. Here is a class that implements that with some of the required functions. I am providing no day light saving details here as this is an example.
class EST(datetime.tzinfo):
def utcoffset(self, dt):
return datetime.timedelta(hours=-5)
def dst(self, dt):
return datetime.timedelta(0)
Now you could use this to get the info with time zone correctness:
print datetime.datetime.now(EST())
Output:
2010-11-01 13:44:20.231259-05:00
The tzinfo
class only defines an interface, you will need to implement it yourself (see the documentation for an example) or use a third-party module which implements it, like pytz
.
Edit: Sorry, I missed that you don't want to import another library.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With