pistacchio
pistacchio

Reputation: 58873

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

Upvotes: 5

Views: 1118

Answers (3)

Phil Cooper
Phil Cooper

Reputation: 5877

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()

Upvotes: 4

Greg Hewgill
Greg Hewgill

Reputation: 993085

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.

Upvotes: 5

Dan P.
Dan P.

Reputation: 179

access the class, create an instance, set your own time, access that object everytime you want the time.

Upvotes: -2

Related Questions