Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Time zones in Python

In a Python application I need to know the current day. datetime.date.today() works well. The problem is that when I deploy the program to my server located in the USA, my user base (that is Italian) is presented a date that may not be the correct one (since the server is 6 time zones away).

How can I construct a date object in python according to a specific time zone? Thanks

like image 942
pistacchio Avatar asked Feb 15 '12 18:02

pistacchio


People also ask

How do I get different time zones in Python?

Use the datetime. astimezone() method to convert the datetime from one timezone to another. This method uses an instance of the datetime object and returns a new datetime of a given timezone.

Which Python library is used for time zone?

The zoneinfo module provides a concrete time zone implementation to support the IANA time zone database as originally specified in PEP 615.

What is the format of time in Python?

strftime(format). The format codes are standard directives for specifying the format in which you want to represent datetime. The%d-%m-%Y%H:%M:%S codes, for example, convert dates to dd-mm-yyyy hh:mm:ss format.


2 Answers

Normally, a server application will do all its time storage and calculations in UTC. Times would also be transmitted to the client in UTC. Then, you do the conversion to local time at the client side (in Javascript, if it's a web application). It's very difficult for a server to get the time zone right for every client, because the server simply doesn't have all the information.

Even if your application is targeted specifically at Italian users, they have been known to travel to other time zones.

like image 57
Greg Hewgill Avatar answered Oct 19 '22 23:10

Greg Hewgill


Everyone agrees that UTC is wonderful but that doesn't help much if datetime.date.today() is being run in the US without a timezone. If the user base is in Italy and that's the date you want to show...

import datetime
import pytz

IT = pytz.timezone('Europe/Rome')
oggi = datetime.now(IT).date()
like image 44
Phil Cooper Avatar answered Oct 20 '22 01:10

Phil Cooper