Time and Timezones in Python

Processing of time information is often a critical part in a Python application. In this post, we are going to solve the following problem:

Given the departure time and the duration of a flight from New York to London, find the arrival time in London local time.

Departure New York: Jul 23 at 19:30, 2018
Flight time: 7h 15min
 
The final output will be


Task: Find the arrival time in London local time.

To solve this problem we need to consider time zones. And that can be a challenge. Time zones are not fixed, they change depending on political decisions. For example, during the summer in New York the time zone respected is EDT (Eastern Daylight Time), but during the winter the time zone EST (Eastern Standard Time) is followed. The situation is similar in London, during summer the BST (British Summer Time) is used and in the winter GMT (Greenwich Mean Time) is followed. When does the summer end and the winter start? Well, that’s not based on meteorological considerations, but on political decisions. And as a consequence, doing time calculation can rapidly escalate into an unmanageable mess of code.

Fortunately, in Python, we have the pytz module which makes time calculations involving time zones a breeze. Pytz can be installed with pip, e.g. in the terminal write pip install pytz.

Specifying a time in Python is a two step process, first we construct a naive datetime object, naive in the sense that it is not aware of the time zone. Next, we make the datetime object timezone aware by using the localize method in the pytz module.The code below shows the calculations with comments.

# Python 3.6.3
import datetime, pytz

# A naive datetime object is constructed by specifying the departure time
departure_time_clock_NewYork = datetime.datetime(2018,7,19,19,30,0)

# To make the datetime object time zone aware, use the localize method
tz_NewYork = pytz.timezone('America/New_York')
departure_time_clock_NewYork = tz_NewYork.localize(departure_time_clock_NewYork)

# The flight duration is
flight_time = datetime.timedelta(hours=7, minutes=15)

# The arival time in London can now be calculated
# Note, this is the arrivale time on the clock in New York

arrival_time_clock_NewYork = departure_time_clock_NewYork + flight_time

# To find the local time we first need the time zone in London
tz_London = pytz.timezone('Europe/London')

# Nex, use the astimezone method to find the local arrival time
arrival_time_clock_London = arrival_time_clock_NewYork.astimezone(tz_London)

# Print the itinerary. We here use of the strftime method
# to clean up the presentation

fmt = '%B %d, %Y %H:%M'

print("Flight BA 176 New York (JFK) to London (LHR)")
print('Depature (JFK):\t{}'.format(departure_time_clock_NewYork.strftime(fmt)))
print('Arrival (LHR):\t{}'.format(arrival_time_clock_London.strftime(fmt)))
print('*** All times are local ***')


And that is all that is needed. Without comments this code is only a few lines long.

 

Comments

  1. Replies
    1. I am glad that I saw this post. It is informative blog for us and we need this type of blog thanks for share this blog, Keep posting such instructional blogs and I am looking forward for your future posts.
      Python Projects for Students

      Data analytics is the study of dissecting crude data so as to make decisions about that data. Data analytics advances and procedures are generally utilized in business ventures to empower associations to settle on progressively Python Training in Chennai educated business choices. In the present worldwide commercial center, it isn't sufficient to assemble data and do the math; you should realize how to apply that data to genuine situations such that will affect conduct. In the program you will initially gain proficiency with the specialized skills, including R and Python dialects most usually utilized in data analytics programming and usage; Python Training in Chennai at that point center around the commonsense application, in view of genuine business issues in a scope of industry segments, for example, wellbeing, promoting and account.

      Project Center in Chennai

      Delete
  2. Best Advanced excel institute in Delhi/Noida is High Technologies Soloutions which provides best training in advanced excel. All the trainers have 5+ years experience in their fields. HTS focus more on practical knowledge than theory which makes training sessions more interesting and trainers focus on individual training as well.HTS provides 100% placement help. Join now!! Call at +919311002620 or visit our website.
    advanced excel course in Delhi
    advanced excel course in Noida

    ReplyDelete
  3. Learn tally from a renowned institute. High technologies Solutions provides the best tally training in Delhi and Noida with 100% placement help. Trainers are subject specialist having 5+ years experience. For free demo class call at +919311002620.
    Tally training institute in delhi
    Tally training institute in Noida

    ReplyDelete
  4. Grow your career with Python in machine learning. High technologies solutions is the best Python training institute in Delhi and Noida with 100% placement help. 5+ years experienced trainers.Join now!! Call at +919311002620.
    Python with machine learning training in delhi
    Python with machine learning training in Noida

    ReplyDelete
  5. High technologies solutions provides the best tally training in Delhi with 100% placement.Trainers are subject specialist and corporate professionals providing in-depth study. 100% placement guaranteed.For free demo class call at +919311002620.
    Tally training institute delhi
    Tally training institute in Noida

    ReplyDelete
  6. High technologies solutions provides the best tally training in Delhi with 100% placement.Trainers are subject specialist and corporate professionals providing in-depth study. 100% placement guaranteed.For free demo class call at +919311002620.
    Tally training institute delhi
    Tally training institute in Noida

    ReplyDelete
  7. High technologies solutions offers the best Autocad training in Delhi and Noida with 100% placement help. Trainers at HTS are friendly, cooperative and subject specialist having more than 5 years of experience.For free demo class Call +919311002620 or visit our website.
    autocad training institute in Delhi
    autocad training institute in Noida

    ReplyDelete
  8. I am glad that I saw this post. It is informative blog for us and we need this type of blog thanks for share this blog, Keep posting such instructional blogs and I am looking forward for your future posts. Python Projects for Students Data analytics is the study of dissecting crude data so as to make decisions about that data. Data analytics advances and procedures are generally utilized in business ventures to empower associations to settle on progressively Python Training in Chennai educated business choices. In the present worldwide commercial center, it isn't sufficient to assemble data and do the math; you should realize how to apply that data to genuine situations such that will affect conduct. In the program you will initially gain proficiency with the specialized skills, including R and Python dialects most usually utilized in data analytics programming and usage; Python Training in Chennai at that point center around the commonsense application, in view of genuine business issues in a scope of industry segments, for example, wellbeing, promoting and account. Project Center in Chennai

    ReplyDelete
  9. Thanks for the information, I agree with this information!

    open commodity trading account

    ReplyDelete
  10. Your post is really good thanks for sharing these kind of post but if anyone looking for Best Consulting Firm for Fake Experience Certificate Providers in bangalore, India with Complete Documents So Dreamsoft Consultancy is the Best Place.Further Details Here- 9599119376 or VisitWebsite-https://experiencecertificates.com/experience-certificate-provider-in-bangalore.html

    ReplyDelete

  11. Great Info, Your blog is very informative and interesting, I really liked while reading your article, the information you have mentioned in this post is really good. I am waiting for your upcoming post your ,post is really good . Otherwise if anyone want to Learn python Course So Contact Us-9311002620 Or check my website- https://www.htsindia.com/Courses/python/python-training-course

    ReplyDelete
  12. This blog is very useful it include very knowledgeable information. Thankyou for sharing this blog with us. If anyone want to experience certificate in bangalore can call at 9599119376 or can visit https://experiencecertificates.com/experience-certificate-provider-in-chennai.html

    ReplyDelete

  13. Your blog is very nice and interesting. Your way of writing this blog forced me to read the full blog. Being a new reader, your blog increased my interest in reading. If anyone is interested for Fake Experience Certificate in Pune here we have the chance for you, Dreamsoft is providing is Fake experience certificate in Pune. To get you experience certificate in Pune you can contact at 9599119376. or can visit our website at https://experiencecertificates.com/experience-certificate-provider-in-pune.html

    ReplyDelete
  14. Your blog is very nice and interesting. Your way of writing this blog forced me to read the full blog. Being a new reader, your blog increased my interest in reading. If anyone is interested for Fake Experience Certificate in Mumbai here we have the chance for you, Dreamsoft is providing is Fake experience certificate in Mumbai. To get you experience certificate in Mumbai you can contact at 9599119376. or can visit our website at https://experiencecertificates.com/experience-certificate-provider-in-mumbai.html

    ReplyDelete
  15. Slot Games and Casino in NC - JTR Hub
    In December, Slot Games and 구리 출장안마 Casino 구리 출장샵 North Carolina 제주도 출장마사지 became the first 태백 출장안마 legal online gambling establishment in the state 양주 출장마사지 with no laws Jan 18, 2020 · Uploaded by JTVH

    ReplyDelete
  16. I always look forward read blogs about python & I want to learn python. Keep sharing this kind of content and write more about python because Python training
    is one of the best ways to get leads in the current time.

    ReplyDelete
  17. Thank you for sharing an amazing & wonderful blog. This content is very useful, informative and valuable in order to enhance knowledge. Keep sharing this type of content with us & keep updating us with new blogs. Apart from this, if anyone who wants to join the C++ Training institute in Delhi, can contact 9311002620 or visit our website-
    https://htsindia.com/Courses/modular-courses/c-plus-plus-training-course

    ReplyDelete
  18. Here's how you can take your possibilities 점보카지노 to win at roulette doing the same. Now, to make issues even simpler for you, here is a list the most well-liked online games of European Roulette. The main distinction between the European and the American roulette is the order of the numbers on the roulette wheel. You don't need to|need not|needn't} deposit anything to play free games with your welcome bonus.

    ReplyDelete
  19. Or, they'll use a CAM program to scan a product prototype to supply the design from. No matter how the design is created, the pc makes use of the digital design to chop components from various supplies. Different CNC machines could also be} Shower Curtains For Kids used to create your half relying on the design and material you need. Our dedication to high quality merchandise, on-time supply, and competitiveness ensures United CNC Machining shall be a valuable asset to your company.

    ReplyDelete
  20. The worth of number playing cards is the same as displayed on the cardboard. The Ace card counts as 1 or 11, relying on whether or not 11 would bust the player/dealer. 온라인 카지노 The supplier will try to stand at or above a value of 17. Players who didn't bust and have an equal or greater card worth than the supplier win; if the supplier busts, anyone who didn't bust wins. Before the players' playing cards are revealed, they can bet 250, 500, 1,000, 5,000, or 10,000 Units on successful.

    ReplyDelete
  21. RESIN– Any of a class Stockings for women of strong or semi-solid organic merchandise of natural or synthetic origin, generally of high molecular weight with no particular melting level. PROTOTYPE MOLD– A simplified mold construction often produced from a lightweight steel casting alloy or from an epoxy resin have the ability to} obtain data for the ultimate mold and/or half design. PRESSURE FORMING– A thermoforming course of wherein stress is used to push the sheet to be formed against the mold surface versus using a vacuum to suck the sheet flat against the mold. PLASTICITY– A property of plastics which permits the fabric to be deformed constantly and completely with out rupture upon the applying of a pressure that exceeds the yield value of the fabric.

    ReplyDelete

Post a Comment

Popular posts from this blog

WinPython - Portable Python that you can run from a usb drive on any Windows machine

Setting up a virtual environment in Python