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
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.
The zoneinfo module provides a concrete time zone implementation to support the IANA time zone database as originally specified in PEP 615.
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.
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.
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()
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With