简体   繁体   中英

Python datetime and daylight saving

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

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

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)

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM