0

My code uses datetime.now() to get current date and time. The problem is that time is 1 hour behind due to daylight saving.

How can I get "real" current time (same I see in system's clock)

Thanks

inspectorG4dget
  • 110,290
  • 27
  • 149
  • 241
Alan Harper
  • 793
  • 1
  • 10
  • 23
  • How do you define "real" time anyway? ;-) The answer posted seems to define "real" time as "unix time" which almost matches UTC time. If you want localtime with DST, then datetime.now() should help. At least it's consistently giving me "correct" time here (CEST). – tobixen Jul 09 '12 at 21:47
  • On my screen I see current date and time ()July 9; 5:49pm - datetime.now returns July 9, 4:49pm – Alan Harper Jul 09 '12 at 21:49
  • Same question here: http://stackoverflow.com/questions/7986776/how-do-you-convert-a-naive-datetime-to-dst-aware-datetime-in-python – AJcodez Jul 09 '12 at 21:49
  • Strange, when I ran `datetime.datetime.now()` at 5:14 CDT, I got `datetime.datetime(2012, 7, 9, 17, 14, 30, 672000)`. Maybe there's something about your system that is affecting the output? – Mark Ransom Jul 09 '12 at 22:18

3 Answers3

0

If you just want the current system time, you could try the time module. time.time() would give you a unix timestamp of the current system time.

Edit: In response to the OP's comment

Use time.strftime() and time.localtime() to interface with datetime objects and your DB

inspectorG4dget
  • 110,290
  • 27
  • 149
  • 241
  • Hi, I need datetime as difference is calculated with a variable from db – Alan Harper Jul 09 '12 at 21:46
  • time.* returns time only; I need date as well – Alan Harper Jul 09 '12 at 21:57
  • Incorrect. `time.localtime()` returns a `time tuple`: `time.struct_time(tm_year=2012, tm_mon=7, tm_mday=9, tm_hour=14, tm_min=47, tm_sec=40, tm_wday=0, tm_yday=191, tm_isdst=1)`. You should really lookup the documentation to make sure that you are correct – inspectorG4dget Jul 09 '12 at 22:06
0

You should read python's datetime doc up to section 8.1 where an example is given on how to achieve what you want.

from datetime import tzinfo, timedelta, datetime
ZERO = timedelta(0)
HOUR = timedelta(hours=1)

# A UTC class.
class UTC(tzinfo):
    """UTC"""

    def utcoffset(self, dt):
        return ZERO

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

    def dst(self, dt):
        return ZERO
utc = UTC()
datetime.now(utc)
Cans
  • 434
  • 3
  • 11
0

I might be completely off, but in case the time in the BIOS your computer is set to UTC (thus the difference of one hour to local time)

datetime.datetime.utcnow()

should yield the time you're looking for.

Klaus-Dieter Warzecha
  • 2,265
  • 2
  • 27
  • 33