utcnow

Joost Molenaar j.j.molenaar at gmail.com
Mon Sep 17 00:44:42 EDT 2012


Time zones! So much fun. Looks like you're dealing with UTC offsets
yourself, which gets messy as soon as you start thinking about DST. The
good news is that there's a timezone database on most systems, which you
should almost definitely use.

Take a look at python-dateutil (pip install python-dateutil):

>>> from datetime import datetime
>>> from dateutil import tz
>>> datetime.now()
datetime.datetime(2012, 9, 17, 6, 33, 57, 158555)

This is a so-called "naive datetime", it doesn't know about timezones. On
my system, it returns a time in my local time zone. (It could have been GMT
or something else entirely.) You have to call .replace() on a "naive
datetime" to set the tzinfo member to make it a timezone-aware datetime
object:

>>> AMS = tz.gettz('Europe/Amsterdam')
>>> ATH = tz.gettz('Europe/Athens')
>>> datetime.now().replace(tzinfo=AMS).astimezone(ATH)
datetime.datetime(2012, 9, 17, 7, 37, 38, 573223,
tzinfo=tzfile('/usr/share/zoneinfo/Europe/Athens'))

Voila, it seems like you're one hour ahead of me. :-)

HTH,

Joost

On 17 September 2012 06:25, Nick the Gr33k <nikos.gr33k at gmail.com> wrote:

> Hello is there a better way of writing this:
>
> date = ( datetime.datetime.utcnow() + datetime.timedelta(hours=3)
> ).strftime( '%y-%m-%d %H:%M:%S')
>
> something like:
>
> date = datetime.datetime.utcnow(**hours=3).strftime( '%y-%m-%d %H:%M:%S')
>
> i prefer it if it could be written as this.
>
> Also what about dayligh savings time?
> --
> http://mail.python.org/**mailman/listinfo/python-list<http://mail.python.org/mailman/listinfo/python-list>
>
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/python-list/attachments/20120917/3bc44b9c/attachment.html>


More information about the Python-list mailing list