Connect with us

AI in Travel

10 Surprising Things You Can Do with Python’s time module

Published

on


10 Surprising Things You Can Do with Python's time module10 Surprising Things You Can Do with Python's time module
Image by Editor | ChatGPT

 

Introduction

 
Most Python developers are familiar with the time module, for its handy functions such as time.sleep(). This makes the modiule the go-to for pausing execution, a simple but essential tool. However, the time module is far more versatile, offering a suite of functions for precise measurement, time conversion, and formatting that often go unnoticed. Exploring these capabilities can unlock more efficient ways to handle time-related tasks in your data science and other coding projects.

I’ve gotten some flack for the naming of previous “10 Surprising Things” articles, and I get it. “Yes, it is so very surprising that I can perform date and time tasks with the datetime module, thank you.” Valid criticism. However, the name is sticking because it’s catchy, so deal with it 🙂

In any case, here are 10 surprising and useful things you can do with Python’s time module.

 

1. Accurately Measure Elapsed Wall-Clock Time with time.monotonic()

 
While you might automatically go for time.time() to measure how long a function takes, it has a critical flaw: it’s based on the system clock, which can be changed manually or by network time protocols. This can lead to inaccurate or even negative time differences. A more robust solution is time.monotonic(). This function returns the value of a monotonic clock, which cannot go backward and is unaffected by system time updates. This really does make it the ideal choice for measuring durations reliably.

import time

start_time = time.monotonic()

# Simulate a task
time.sleep(2)

end_time = time.monotonic()
duration = end_time - start_time

print(f"The task took {duration:.2f} seconds.")

 

Output:

The task took 2.01 seconds.

 

2. Measure CPU Processing Time with time.process_time()

 
Sometimes, you don’t care about the total time passed (wall-clock time). Instead, you might want to know how much time the CPU actually spent executing your code. This is crucial for benchmarking algorithm efficiency, as it ignores time spent sleeping or waiting for I/O operations. The time.process_time() function returns the sum of the system and user CPU time of the current process, providing a pure measure of computational effort.

import time

start_cpu = time.process_time()

# A CPU-intensive task
total = 0
for i in range(10_000_000):
    total += i

end_cpu = time.process_time()
cpu_duration = end_cpu - start_cpu

print(f"The CPU-intensive task took {cpu_duration:.2f} CPU seconds.")

 

Output:

The CPU-intensive task took 0.44 CPU seconds.

 

3. Get High-Precision Timestamps with time.perf_counter()

 
For highly precise timing, especially for very short durations, time.perf_counter() is an essential tool. It returns the value of a high-resolution performance counter, which is the most accurate clock available on your system. This is a system-wide count, including time elapsed during sleep, which makes it perfect for benchmark scenarios where every nanosecond counts.

import time

start_perf = time.perf_counter()

# A very short operation
_ = [x*x for x in range(1000)]

end_perf = time.perf_counter()
perf_duration = end_perf - start_perf

print(f"The short operation took {perf_duration:.6f} seconds.")

 

Output:

The short operation took 0.000028 seconds.

 

4. Convert Timestamps to Readable Strings with time.ctime()

 
The output of time.time() is a float representing seconds since the “epoch” (January 1, 1970, for Unix systems). While useful for calculations, it’s not human-readable. The time.ctime() function takes this timestamp and converts it into a standard, easy-to-read string format, like ‘Thu Jul 31 16:32:30 2025’.

import time

current_timestamp = time.time()
readable_time = time.ctime(current_timestamp)

print(f"Timestamp: {current_timestamp}")
print(f"Readable Time: {readable_time}")

 

Output:

Timestamp: 1754044568.821037
Readable Time: Fri Aug  1 06:36:08 2025

 

5. Parse Time from a String with time.strptime()

 
Let’s say you have time information stored as a string and need to convert it into a structured time object for further processing. time.strptime() (string parse time) is your function. You provide the string and a format code that specifies how the date and time components are arranged. It returns a struct_time object, which is a tuple containing elements — like year, month, day, and so on — which can then be extracted.

import time

date_string = "31 July, 2025"
format_code = "%d %B, %Y"

time_struct = time.strptime(date_string, format_code)

print(f"Parsed time structure: {time_struct}")
print(f"Year: {time_struct.tm_year}, Month: {time_struct.tm_mon}")

 

Output:

Parsed time structure: time.struct_time(tm_year=2025, tm_mon=7, tm_mday=31, tm_hour=0, tm_min=0, tm_sec=0, tm_wday=3, tm_yday=212, tm_isdst=-1)
Year: 2025, Month: 7

 

6. Format Time into Custom Strings with time.strftime()

 
The opposite of parsing is formatting. time.strftime() (string format time) takes a struct_time object (like the one returned by strptime or localtime) and formats it into a string according to your specified format codes. This gives you full control over the output, whether you prefer “2025-07-31” or “Thursday, July 31”.

import time

# Get current time as a struct_time object
current_time_struct = time.localtime()

# Format it in a custom way
formatted_string = time.strftime("%Y-%m-%d %H:%M:%S", current_time_struct)
print(f"Custom formatted time: {formatted_string}")

day_of_week = time.strftime("%A", current_time_struct)
print(f"Today is {day_of_week}.")

 

Output:

Custom formatted time: 2025-08-01 06:41:33
Today is Friday

 

7. Get Basic Timezone Information with time.timezone and time.tzname

 
While the datetime module (and libraries like pytz) are better for complex timezone handling, the time module offers some basic information. time.timezone provides the offset of the local non-DST (Daylight Savings Time) timezone in offset seconds west of UTC, while time.tzname is a tuple containing the names of the local non-DST and DST timezones.

import time

# Offset in seconds west of UTC
offset_seconds = time.timezone

# Timezone names (standard, daylight saving)
tz_names = time.tzname

print(f"Timezone offset: {offset_seconds / 3600} hours west of UTC")
print(f"Timezone names: {tz_names}")

 

Output:

Timezone offset: 5.0 hours west of UTC
Timezone names: ('EST', 'EDT')

 

8. Convert Between UTC and Local Time with time.gmtime() and time.localtime()

 
Working with different timezones can be tricky. A common practice is to store all time data in Coordinated Universal Time (UTC) and convert it to local time only for display. The time module facilitates this with time.gmtime() and time.localtime(). These functions take a timestamp in seconds and return a struct_time object — gmtime() returns it in UTC, while localtime() returns it for your system’s configured timezone.

import time

timestamp = time.time()

# Convert timestamp to struct_time in UTC
utc_time = time.gmtime(timestamp)

# Convert timestamp to struct_time in local time
local_time = time.localtime(timestamp)

print(f"UTC Time: {time.strftime('%Y-%m-%d %H:%M:%S', utc_time)}")
print(f"Local Time: {time.strftime('%Y-%m-%d %H:%M:%S', local_time)}")

 

Output:

UTC Time: 2025-08-01 10:47:58
Local Time: 2025-08-01 06:47:58

 

9. Perform the Inverse of time.time() with time.mktime()

 
time.localtime() converts a timestamp into a struct_time object, which is useful… but how do you go in the reverse direction? The time.mktime() function does exactly this. It takes a struct_time object (representing local time) and converts it back into a floating-point number representing seconds since the epoch. This is then useful for calculating future or past timestamps or performing date arithmetic.

import time

# Get current local time structure
now_struct = time.localtime()

# Create a modified time structure for one hour from now
future_struct_list = list(now_struct)
future_struct_list[3] += 1 # Add 1 to the hour (tm_hour)
future_struct = time.struct_time(future_struct_list)

# Convert back to a timestamp
future_timestamp = time.mktime(future_struct)

print(f"Current timestamp: {time.time():.0f}")
print(f"Timestamp in one hour: {future_timestamp:.0f}")

 

Output:

Current timestamp: 1754045415
Timestamp in one hour: 1754049015

 

10. Get Thread-Specific CPU Time with time.thread_time()

 
In multi-threaded applications, time.process_time() gives you the total CPU time for the entire process. But what if you want to profile the CPU usage of a specific thread? In this case, time.thread_time() is the function you are looking for. This function returns the sum of system and user CPU time for the current thread, allowing you to identify which threads are the most computationally expensive.

import time
import threading

def worker_task():
    start_thread_time = time.thread_time()

    # Simulate work
    _ = [i * i for i in range(10_000_000)]

    end_thread_time = time.thread_time()

    print(f"Worker thread CPU time: {end_thread_time - start_thread_time:.2f}s")

# Run the task in a separate thread
thread = threading.Thread(target=worker_task)
thread.start()
thread.join()

print(f"Total process CPU time: {time.process_time():.2f}s")

 

Output:

Worker thread CPU time: 0.23s
Total process CPU time: 0.32s

 

Wrapping Up

 
The time module is an integral and powerful segment of Python’s standard library. While time.sleep() is undoubtedly its most famous function, its capabilities for timing, duration measurement, and time formatting make it a handy tool for all sorts of practically-useful tasks.

By moving beyond the basics, you can learn new tricks for writing more accurate and efficient code. For more advanced, object-oriented date and time manipulation, be sure to check out surprising things you can do with the datetime module next.
 
 

Matthew Mayo (@mattmayo13) holds a master’s degree in computer science and a graduate diploma in data mining. As managing editor of KDnuggets & Statology, and contributing editor at Machine Learning Mastery, Matthew aims to make complex data science concepts accessible. His professional interests include natural language processing, language models, machine learning algorithms, and exploring emerging AI. He is driven by a mission to democratize knowledge in the data science community. Matthew has been coding since he was 6 years old.





Source link

Continue Reading
Click to comment

You must be logged in to post a comment Login

Leave a Reply

AI in Travel

Tourism New Zealand Pioneers Future of Travel with AI-Powered Minecraft Destination – What You Need to Know

Published

on


Sunday, August 3, 2025

Tourism New Zealand has taken a bold step into the future of travel by combining artificial intelligence (AI) and gaming to transform how people plan their trips. In a groundbreaking initiative, New Zealand has become the world’s first fully playable country within Minecraft, marking a major shift in destination marketing. This AI-powered Minecraft destination merges the growing popularity of gaming with travel, offering a digital experience that inspires real-world visits.

AI-Powered Trip Planner

In partnership with GuideGeek, an AI-powered travel assistant, Tourism New Zealand has integrated an intuitive trip planner directly into its website, newzealand.com. This AI assistant is designed to break down the common barriers to travel planning, providing answers to common questions such as “How long is the flight to New Zealand?” or “What are the best activities to do in each season?” It offers personalized suggestions based on user preferences, helping travelers plan their journeys with ease.

The AI platform is driven by a massive database of tourism data from regional organizations and local operators, ensuring that every response is accurate and tailored. This technology not only simplifies the planning process but also encourages deeper interaction with the destination, moving beyond simple queries to a more personalized experience. By leveraging GuideGeek, Tourism New Zealand offers a travel planning tool that is intuitive, data-driven and highly effective.

A Virtual New Zealand in Minecraft

A core component of this campaign is the launch of Aotearoa New Zealand DLC within Minecraft. In collaboration with Mojang Studios and other local partners, Tourism New Zealand has transformed the country’s iconic landscapes into a fully interactive, digital version within the game. Landmarks such as the Waitomo Caves and Abel Tasman National Park can now be explored virtually by players worldwide.

This initiative was launched alongside the release of A Minecraft Movie, amplifying the excitement and engagement around the digital New Zealand. Players can virtually paddle a traditional Māori waka or explore the famous glowworm caves, experiencing New Zealand’s natural wonders and culture in a way that was never possible before. This immersive virtual experience is designed to captivate users, sparking curiosity about the real-world destinations that these locations represent.

Driving Real-World Travel

The integration of AI and Minecraft has proven to be a successful formula in engaging potential travelers. Since its launch, the AI trip planner has been used by over 200,000 unique visitors, with those interacting with the platform showing a 600% higher engagement rate compared to average users. This indicates a growing interest in using AI tools to enhance travel planning.

The Minecraft integration has also brought significant attention to New Zealand, with over 50,000 active users continuing to explore the digital destination. This engagement not only strengthens the appeal of New Zealand as a travel destination but also demonstrates the effectiveness of blending gaming with tourism marketing.

Looking to the Future of Travel

Tourism New Zealand is setting the standard for the future of travel. This AI-powered Minecraft experience demonstrates how gaming and artificial intelligence can be used creatively to attract and engage travelers. By leveraging these technologies, New Zealand is not only offering a unique way for potential visitors to explore the country virtually, but also inspiring them to experience it in person.

As the travel industry continues to evolve, the use of AI and gaming is likely to become an integral part of tourism marketing strategies worldwide. Tourism New Zealand’s initiative showcases the potential for innovation in the travel industry, positioning the country as a leader in the future of travel.



Source link

Continue Reading

AI in Travel

Tourism Malaysia And HONOR Malaysia Collaborate To Promote Visit Malaysia 2026 Through AI Technology

Published

on


Saturday, August 2, 2025

Tourism Malaysia has teamed up with HONOR Technology (Malaysia) to change how the country promotes tourism. Through a Memorandum of Collaboration (MoC), both organizations will use new technology, specifically AI-driven digital storytelling, to improve Malaysia’s visibility in global tourism. This partnership aims to increase Malaysia’s presence in the international tourism market, especially ahead of the upcoming Visit Malaysia 2026 (VM2026) campaign.

A Game-Changing Collaboration

The partnership between Tourism Malaysia and HONOR Malaysia marks a significant shift in the tourism industry’s approach to promotional strategies. As the tourism sector increasingly embraces technological advancements, this collaboration is a prime example of how innovation can be leveraged to meet modern demands. Both organizations are committed to utilizing AI-powered technology to create engaging, interactive, and visually stunning content that will appeal to a broad audience, particularly the younger, digitally savvy generation.

Through the use of HONOR’s advanced AI-powered mobile technology, the partnership will deliver a series of creative initiatives designed to engage local and international audiences. The aim is to connect with travelers in a more dynamic, personal way, leveraging AI to produce content that is not only visually striking but also reflective of the diverse cultural and scenic beauty of Malaysia.

Key Initiatives Under the Partnership

The collaboration will kick off with a series of interactive campaigns designed to bring Malaysia’s most iconic tourist attractions to the forefront. One of the standout features of the partnership is a nationwide photography competition that will invite both local and international participants to capture Malaysia’s stunning landscapes and cultural landmarks. HONOR’s AI-enhanced smartphones will be the primary tool for participants, enabling them to capture high-quality images that showcase the country’s rich diversity.

In addition to the photography competition, the initiative will include guided photo tours at major tourist spots across Malaysia, giving travelers the opportunity to explore the country’s beauty through the lens of a professional photographer. These tours will provide participants with valuable insights into the history, culture, and natural wonders of Malaysia, helping to foster a deeper connection to the country.

Another highlight of the collaboration will be creative workshops, where industry experts will guide participants through the process of creating compelling travel content. These workshops will provide attendees with the skills they need to produce high-quality digital content, from photography to video production, all while highlighting Malaysia’s attractions. The workshops will also serve as a platform for cultural exchange, allowing local and international participants to share their experiences and ideas.

Furthermore, the collaboration will feature art exhibitions showcasing AI-enhanced visuals captured using HONOR smartphones. These exhibitions will offer a new perspective on Malaysia’s tourism offerings, blending technology with art to create visually captivating displays. The exhibitions will serve as both a celebration of Malaysia’s cultural heritage and a forward-thinking approach to tourism marketing.

The Role of AI and Mobile Technology

HONOR Malaysia’s role in this collaboration is crucial, as the company’s mobile technology and AI capabilities will be integral to curating visually compelling content. By utilizing AI-powered features such as scene recognition and photo enhancement, the smartphones will enable users to create professional-quality images with ease. This approach not only highlights the beauty of Malaysia but also encourages travelers to explore the country’s destinations in a more immersive way.

Tourism Malaysia’s involvement in the partnership focuses on facilitating access to the country’s top tourist attractions, providing logistical support, and amplifying the campaign’s reach through its extensive global tourism network. The government agency has long been at the forefront of efforts to promote Malaysia as a top tourist destination, and this collaboration with HONOR represents a new chapter in the country’s tourism marketing strategy.

Embracing Innovation to Appeal to Global Audiences

As Malaysia prepares for the Visit Malaysia 2026 campaign, the collaboration between Tourism Malaysia and HONOR Malaysia is a timely step towards modernizing the country’s approach to tourism promotion. By embracing AI and mobile creativity, the initiative aims to engage younger, tech-savvy travelers who are increasingly seeking interactive and personalized travel experiences. The partnership also aligns with global marketing trends, as more and more brands leverage digital platforms and emerging technologies to connect with consumers.

This collaboration is a significant move in ensuring that Malaysia’s tourism industry remains competitive in the global market. By focusing on user-generated content and encouraging creativity, the campaign aims to not only promote Malaysia’s scenic beauty and cultural richness but also foster emotional and visual connections with travelers worldwide. The campaign’s use of AI and technology ensures that Malaysia’s tourism offerings are showcased in a modern, dynamic light, capturing the attention of audiences across the globe.

Strengthening Public-Private Partnerships for Tourism Growth

The collaboration between Tourism Malaysia and HONOR Malaysia exemplifies the power of public-private partnerships in driving tourism growth. By combining the expertise and resources of both organizations, the partnership is poised to make a significant impact on Malaysia’s tourism sector. This MoC is also a testament to the growing recognition of the importance of innovation and technology in shaping the future of travel marketing.

As the Visit Malaysia 2026 campaign approaches, the collaboration is set to serve as a benchmark for how technology can be integrated into tourism promotion. The initiative will not only help boost Malaysia’s visibility in the global tourism market but also inspire other nations to embrace technology as a means of enhancing their tourism offerings. By blending tradition with innovation, Tourism Malaysia and HONOR Malaysia are setting a new standard for the future of travel marketing.

A Groundbreaking Step

In conclusion, the partnership between Tourism Malaysia and HONOR Malaysia is a significant move toward changing how tourism is promoted in the digital age. By using AI-driven digital storytelling and mobile technology, the collaboration seeks to improve Malaysia’s presence in global tourism and involve both local and international audiences in engaging and creative ways. As the Visit Malaysia 2026 campaign approaches, this partnership represents the changing connection between technology and tourism, paving the way for a more immersive and interactive travel experience for everyone.



Source link

Continue Reading

AI in Travel

Revival of Ansett Australia with AI – What You Need to Know

Published

on


Saturday, August 2, 2025

The Revival of Ansett Australia has taken a surprising turn, formerly one of the leading airlines in Australia has made an incredible comeback – albeit not as a full-service airline. The reintroduction of the airline was conceived by Melbourne entrepreneur, Constantine Frantzekos who saw an opportunity to reinvigorate the Ansett name and offer a more tailored and cost-effective means of flying, Through the platform, known as Ansett. Travel, powered by cutting-edge artificial intelligence, Frantzekos aims to transform how Australians plan and experience travel, bringing back the legacy of Ansett in a modern, digital form.

From Airline to AI Travel Platform

Launched many decades ago Ansett quickly became a household name and was most noted for its innovative flight experience coupled with world-leading customer service. But after it folded in 2001, the brand appeared to never fly again. But Frantzekos spied an opportunity in the moldering trademark, which had expired. Rather than siphoning the defunct airline’s DNA, he rebuilt the brand as an ultra-modern travel tech platform that prides itself on deep personalization and machine learning to serve 21st-century travelers’ changing needs.

AI-Driven Personalization for Modern Travelers

Ansett. Travel, Australia’s first travel agency wholly powered by A.I. The platform seeks to provide a more intelligent and personalized experience by mining users’ preferences using algorithms and machine learning. The AI makes personalized travel recommendations for trips, activities and experiences over time — it’s like your own personal travel concierge in the cloud. Users enter information about their travel experience — like the location, dates and interests at play—and an AI powered program conjures up bespoke itineraries, activities and amenities for them.

For instance, a user could plan for having their mate from Melbourne visit them to watch a major sports event such as the Ashes. The AI would then suggest things to do in the area and local accommodations/restaurants that suit their tastes. Private Charter Members also get the benefit of buying these services at very close to wholesale on Ansett VIP.

An Affordable Business Model Focused on Savings

The business model behind Ansett. Travel is based on two pillars, deep personalization and affordability. Users can enroll in a VIP membership for $99 per year, which entails discounts on flights, hotels and cultural experiences. The platform is planned to provide dramatic savings when compared against old fashioned travel agencies that are expensive in terms of overheads and staff. Instead, Ansett leverages technology to automate all of its operations and invests capital into building a platform while keeping a tiny support team.

Ansett is not a traditional travel agency, which can take the bulk of a dollar when it sells and then enjoys large profit margins. The website intentionally makes their pricing more competitive for travelers and leaves the difference in savings right up on company’s frontpage.

Combining AI with Human Support

Frantzekos draws parallels between Ansett. Travel and companies like Uber, which have bet on personalized service without traditional overhead. The service features a Chrome and Firefox extension (with Safari support coming) that lets consumers compare real-time prices on travel products while visiting other sites.

Despite being AI-driven, Ansett. Travel also reminds you how essential human contact is. With AI responsible for the majority of routine personalization duties, customer support agents can be on hand to help users when there are specific problems or they need assistance urgently. It is this melding of AI efficiency and human hospitality that makes for a smoother travel experience.

What Next, The Future of Ansett

While Ansett. Travel isn’t an airline, but Frantzekos says he wouldn’t rule out possibly branching the brand into air travel in some way down the line. For now he wants to give every Australian access to a next-level travel concierge that aspires on the nostalgia of Ansett with modern AI power. Ansett Australia is reborn in the Digital world, not flying but at the forefront of a new era, transforming travel using blockchain technology.



Source link

Continue Reading

Trending

Copyright © 2025 AISTORIZ. For enquiries email at prompt@travelstoriz.com