Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python - datetime of a specific timezone

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.

like image 281
wuntee Avatar asked Nov 01 '10 18:11

wuntee


People also ask

How do I convert datetime to different timezone in Python?

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.

How do you read time zones by datetime?

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.

What timezone does Python datetime use?

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.

How do I make datetime TZ aware?

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.


2 Answers

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 
like image 157
pyfunc Avatar answered Oct 08 '22 17:10

pyfunc


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.

like image 43
adw Avatar answered Oct 08 '22 17:10

adw