6

I'm utilizing the datetime module to produce the current date. However, when I run this after 7PM, the current date becomes tomorrow's date.

I'm not sure how to set the time zone for the following module

from datetime import *
print date.today()

I've read the documentation but have not found how to set this yet.

Chris
  • 5,444
  • 16
  • 63
  • 119

2 Answers2

20

Your date is a "naive" datetime, it doesn't have a timezone (tz=None). Then you have to localize this datetime by setting a timezone. Use pytz module to do that.

Here is an example :

from datetime import datetime
from pytz import timezone
# define date format
fmt = '%Y-%m-%d %H:%M:%S %Z%z'
# define eastern timezone
eastern = timezone('US/Eastern')
# naive datetime
naive_dt = datetime.now()
# localized datetime
loc_dt = datetime.now(eastern)
print(naive_dt.strftime(fmt))
# 2015-12-31 19:21:00 
print(loc_dt.strftime(fmt))
# 2015-12-31 19:21:00 EST-0500

Read pytz documentation for more information

Louis Barranqueiro
  • 10,058
  • 6
  • 42
  • 52
3

While date doesn't have a way to select a time zone, datetime does. You need to create a subclass of tzinfo with the information for your desired time zone:

class UTC(tzinfo):
    def utcoffset(self, dt):
        return timedelta(0)

    def tzname(self, dt):
        return "UTC"

    def dst(self, dt):
        return timedelta(0) 

For example, the Eastern Standard Time (UTC-5:00, no DST):

class EST(tzinfo):
    def utcoffset(self, dt):
        return timedelta(hours = -5)

    def tzname(self, dt):
        return "EST"

    def dst(self, dt):
        return timedelta(0)

After making a class for your timezone, you would then get the date you wanted with:

datetime.now(UTC()).date()

(Replace UTC with your timezone class name)

There is also a library available, pytz, that would make this much easier for you.

user44294
  • 31
  • 3
  • US Eastern time is only -5 during *standard* time. It switches to -4 when *daylight* time is in effect. Hence the necessity for libraries like pytz. – Matt Johnson-Pint Dec 31 '15 at 21:24
  • @MattJohnson It's just an example, but I used _EST_ for that reason. EST is always UTC-5, EDT is always UTC-4, ET switches between the two. – user44294 Dec 31 '15 at 21:32
  • Exactly. The OP asked for "eastern". Of course they could be talking about eastern time in *australia* as well. lol. :) – Matt Johnson-Pint Dec 31 '15 at 21:36
  • @MattJohnson I see your confusion now. I edited it to hopefully make it more clear that EST was just an example, not meant to actually be the OP's timezone. – user44294 Dec 31 '15 at 21:45
  • 1
    how do you suggest to choose between EST and EDT? [Use the tz database instead: `datetime.now(pytz.timezone('America/New_York')).date()`](http://stackoverflow.com/a/25887393/4279). It finds the correct utc offset for the current date automatically. – jfs Jan 01 '16 at 02:16