Connect with us

Jobs & Careers

10 Surprising Things You Can Do with Python’s datetime Module

Published

on


10 Surprising Things You Can Do with Python's datetime Module
Image by Author | ChatGPT

 

Introduction

 
Python’s built-in datetime module can easily be considered the go-to library for handling date and time formatting and manipulation in the ecosystem. Most Python coders are familiar with creating datetime objects, formatting them into strings, and performing basic arithmetic. However, this powerful module, sometimes alongside related libraries such as calendar, offers a ton more functionality beyond the basics that can solve complex date and time-related problems with surprising ease.

This article looks at 10 useful — and perhaps surprising — things you can accomplish with Python’s datetime module. From navigating timezones to calculating specific weekday occurrences, these examples will demonstrate the versatility of Python’s date and time toolkit.

 

1. Finding the Day of the Week

 
Beyond just knowing the date, you often need to know the day of the week. The datetime module makes this trivial. Every datetime object has a weekday() method, which returns the day of the week as an integer (Monday is 0, Sunday is 6), and a strftime() method, which can format the date to show the full day name.

import datetime

# Pick a date
today = datetime.date(2025, 7, 10)

# Get the day of the week (Monday is 0)
day_of_week_num = today.weekday()
print(f"Day of the week (numeric): {day_of_week_num}")

# Get the full name of the day
day_name = some_date.strftime("%A")
print(f"The date {today} is a {day_name}")

 

Output:

The date 2025-07-10 is a Thursday

 

2. Calculating the Time Until a Future Event

 
Ever needed a simple countdown timer? With datetime, you can easily calculate the time remaining until a specific future date and time. By subtracting the current datetime from a future one, you get a timedelta object that represents the difference.

import datetime

# Define a future event
new_year_2050 = datetime.datetime(2050, 1, 1, 0, 0, 0)

# Get the current time
now = datetime.datetime.now()

# Calculate the difference
time_left = new_year_2050 - now

print(f"Time left until New Year 2050: {time_left}")

 

Output:

Time left until New Year 2050: 8940 days, 16:05:52.120836

 

3. Working with Timezones

 
Handling timezones is tricky. A naive datetime object has no timezone data, while an aware object does possess this data. Using the pytz library (or the built-in zoneinfo in Python 3.9+) makes working with timezones manageable.

For instance, you can use one timezone’s time as a base for conversion to another timezone like this:

import datetime
from pytz import timezone

# Create a timezone-aware datetime for New York
nyc_tz = timezone('America/New_York')
nyc_time = datetime.datetime.now(nyc_tz)
print(f"New York Time: {nyc_time}")

# Convert it to another timezone
london_tz = timezone('Europe/London')
london_time = nyc_time.astimezone(london_tz)
print(f"London Time: {london_time}")

 

Output:

New York Time: 2025-07-10 07:57:53.900220-04:00
London Time: 2025-07-10 12:57:53.900220+01:00

 

4. Getting the Last Day of a Month

 
Figuring out the last day of a month is not straightforward since months have different numbers of days. You could write logic to handle 30/31 days along with February (don’t forget about leap years!), or you could use a clever trick with datetime and timedelta. The strategy is to find the first day of the next month and then subtract one day.

import datetime

def get_last_day_of_month(year, month):
    # Handle month rollover for December -> January
    if month == 12:
        next_month_first_day = datetime.date(year + 1, 1, 1)
    else:
        next_month_first_day = datetime.date(year, month + 1, 1)
    
    # Subtract one day to get the last day of the current month
    return next_month_first_day - datetime.timedelta(days=1)

# Example: Get the last day of February 2024 (a leap year)
last_day = get_last_day_of_month(2024, 2)
print(f"The last day of February 2024 is: {last_day}")

 

Output:

The last day of February 2024 is: 2024-02-29

 

5. Calculating Your Precise Age

 
You can use datetime to calculate someone’s age down to the day. The logic involves subtracting the birthdate from the current date and then performing a small adjustment to account for whether the person’s birthday has occurred yet this year.

import datetime

def calculate_age(birthdate):
    today = datetime.date.today()
    age = today.year - birthdate.year - ((today.month, today.day) < (birthdate.month, birthdate.day))
    return age

# Example usage
picasso_birthdate = datetime.date(1881, 10, 25)
picasso_age = calculate_age(picasso_birthdate)
print(f"If alive today, Pablo Picasso would be {picasso_age} years old.")

 

Output:

If alive today, Pablo Picasso would be 143 years old.

 

6. Iterating Through a Range of Dates

 
Sometimes you need to perform an operation for every day within a specific date range. You can easily loop through dates by starting with a date object and repeatedly adding a timedelta of one day until you reach the end date.

import datetime

start_date = datetime.date(2025, 1, 1)
end_date = datetime.date(2025, 1, 7)
day_delta = datetime.timedelta(days=1)

current_date = start_date
while current_date <= end_date:
    print(current_date.strftime('%Y-%m-%d, %A'))
    current_date += day_delta

 

Output:

2025-01-01, Wednesday
2025-01-02, Thursday
2025-01-03, Friday
2025-01-04, Saturday
2025-01-05, Sunday
2025-01-06, Monday
2025-01-07, Tuesday

 

7. Parsing Dates from Non-Standard String Formats

 
The strptime() function is useful for converting strings to datetime objects. It is incredibly flexible and can handle a wide variety of formats by using specific format codes. This is essential when dealing with data from different sources that may not use a standard ISO format.

import datetime

date_string_1 = "July 4, 1776"
date_string_2 = "1867-07-01 14:30:00"

# Parse the first string format
dt_object_1 = datetime.datetime.strptime(date_string_1, "%B %d, %Y")
print(f"Parsed object 1: {dt_object_1}")

# Parse the second string format
dt_object_2 = datetime.datetime.strptime(date_string_2, "%Y-%m-%d %H:%M:%S")
print(f"Parsed object 2: {dt_object_2}")

 

Output:

Parsed object 1: 1776-07-04 00:00:00
Parsed object 2: 1867-07-01 14:30:00

 

8. Finding the Nth Weekday of a Month

 
Do you want to know the date of the third Thursday in November? The calendar module can be used alongside datetime to solve this. The monthcalendar() function returns a matrix representing the weeks of a month, which you can then parse.

import calendar

# calendar.weekday() Monday is 0 and Sunday is 6
# calendar.Thursday is 3
cal = calendar.Calendar()

# Get a matrix of weeks for November 2025
month_matrix = cal.monthdatescalendar(2025, 11)

# Find the third Thursday
third_thursday = [week[calendar.THURSDAY] for week in month_matrix if week[calendar.THURSDAY].month == 11][2]

print(f"The third Thursday of Nov 2025 is: {third_thursday}")

 

Output:

The third Thursday of Nov 2025 is: 2025-11-20

 

9. Getting the ISO Week Number

 
The ISO 8601 standard defines a system for week numbering where a week starts on a Monday. The isocalendar() method returns a tuple containing the ISO year, week number, and weekday for a given date.

Note that the date below is a Thursday, and so should result in a day of the week of 4. It should also be the 28th week of the year.

import datetime

d = datetime.date(2025, 7, 10)
iso_cal = d.isocalendar()

print(f"Date: {d}")
print(f"ISO Year: {iso_cal[0]}")
print(f"ISO Week Number: {iso_cal[1]}")
print(f"ISO Weekday: {iso_cal[2]}")

 

Output:

Date: 2025-07-10
ISO Year: 2025
ISO Week Number: 28
ISO Weekday: 4

 

10. Adding or Subtracting Business Days

 
Calculating future dates while skipping weekends is a common business requirement. While datetime doesn’t have a built-in function for this, you can write a simple helper function using timedelta and the weekday() method.

import datetime

def add_business_days(start_date, num_days):
    current_date = start_date
    while num_days > 0:
        current_date += datetime.timedelta(days=1)
        # weekday() returns 5 for Saturday and 6 for Sunday
        if current_date.weekday() < 5:
            num_days -= 1
    return current_date

start = datetime.date(2025, 7, 10) # A Thursday
end = add_business_days(start, 13)

print(f"13 business days after {start} is {end}")

 

13 business days after 2025-07-10 is 2025-07-29

 

Wrapping Up

 
Python’s datetime module is more than just a simple tool for storing dates. It provides a flexible and useful set of tools for handling almost any time-related logic imaginable. By understanding its core components — date, time, datetime, and timedelta — and combining them with the calendar module or external libraries like pytz, you can solve complex real-world problems efficiently and accurately.

Don’t forget to check out the datetime module’s documentation for more. You might be surprised at what you can accomplish.
 
 

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

Leave a Reply

Your email address will not be published. Required fields are marked *

Jobs & Careers

5 Strategic Steps to a Seamless AI Integration

Published

on


Sponsored Content

 

 
5 Strategic Steps to a Seamless AI Integration
 

Predictive text and autocorrect when you’re sending an SMS or email; Real-time traffic and fastest routes suggestion with Google/Apple Maps; Setting alarms and controlling smart devices using Siri and Alexa. These are just a few examples of how humans utilize AI. Often unseen, but AI now powers almost everything in our lives.

That’s why the enterprises globally have also been favoring and supporting its implementation. According to the latest survey by McKinsey, 78 percent of respondents report that their organizations use AI in at least one business function. Respondents most often report using the technology in IT, marketing, and sales functions, as well as other service operations. AI is growing because it brings a transformative edge.

But truly harnessing AI’s potential requires meticulous integration. Many AI projects stall after pilot phases. Some of the reasons include misaligned priorities, poor data readiness, and cultural readiness. In the upcoming sections, we’ll explore how businesses can embed new-age intelligence more effectively.

 

What is AI Adoption?

 

It simply means using AI technologies in an organization’s workflow, systems, and decision-making processes. From writing a quick email to preparing a PowerPoint presentation to analyzing customer data, AI integration enhances all facets of performance.

Consider a food delivery app. AI integration can optimize delivery routes in real time. Reduce food waste. Personalize restaurant recommendations. Forecast demand spikes. Detect fraudulent transactions. But how do you foster this crucial cultural shift in your line of business while driving competitive advantage? Leaders can adhere to a structured roadmap (five strategic steps) to get started.

 

Five Steps to Successful AI Integration

 

 

Step 1: What Are You Trying to Solve?

 

AI integration should always begin with a clearly defined strategic purpose. However, organizations often pursue AI for its novelty. Because competitors are already experimenting with it. And no one wants to be left behind. In that pursuit, businesses undertake AI initiatives, which often end up becoming isolated pilots that never scale.

Instead, ask questions like, “What measure value can AI unlock? Which KPIs will define success?” For instance, if the objective is to personalize customer experiences, then the AI initiative should focus on:

  • Recommending the right products
  • Tailoring communication
  • Providing an omnichannel experience
  • Predicting customer needs

That’s why defining the core problem first is so important. It informs subsequent decisions. An AI consulting partner can also help you get it right.

 

Step 2: Build a Strong Data Foundation

 

AI learns from historical data. And sometimes, that data might reflect the world’s imperfections. One example of this is the AI recruitment tool that Amazon onboarded some time ago. It was trained on a dataset containing resumes mostly from male candidates. And AI interpreted that women candidates are less preferable. It was later scraped. However, this highlights that any bias or inaccuracies in the data can impact the outcome. Read more on how to implement responsible AI.

That’s why cleansing and labeling data is essential to reduce errors and bias. That said, to maximize extracting value from current internal data assets, enterprises also need to:

  • Consolidate siloed sources into centralized, shareable data lakes
  • Establish data governance protocols covering ownership, compliance, and security

 

Step 3: Train Your Employees

 

Will AI take away my job? This is one of the most asked questions by people working in the services sector today. While AI has its merits in taking over rote tasks, it can’t replace human intelligence and experience. That’s why there’s a need for careful adaptation. Employees need to take on new responsibilities such as:

  • Interpreting AI insights to inform decisions
  • Taking more strategic initiatives
  • Working in tandem with AI

This will help people feel safer with their jobs and harness the potential of AI more efficiently.

 

Step 4: Start Small, Scale Smart

 

Large-scale, enterprise-wide AI rollouts may seem like a tempting choice, but they are seldom a good fit. Instead, small, high-impact pilots should be the go-to approach. For instance, instead of integrating AI immediately across the entire marketing division in the business, let marketing heads and some executives from various niches participate in it. Test a hypothesis or perform a comparative analysis (just an example). Measure the efficacy of those who used AI tools vs those who worked without it for a week?

Metrics can be speed, accuracy, output, and results. If the winner is the group that uses AI, then scale this project further. This helps:

  • Build organizational confidence in AI
  • Provides measurable ROI early on
  • Minimizes risks of operational disruption by testing first

 

Step 5: Embed Responsible and Ethical AI Practices

 

Trust is the cornerstone of AI integration. As all AI systems interact with people, businesses must ensure that their models operate ethically, responsibly, and securely. To get started:

  • Conduct algorithmic audits to assess for bias
  • Enabling explainability features so users understand why a model made that decision
  • Ensure clear communication about how AI is used and the data it relies on

These five steps can help you build and integrate responsible and intelligent AI systems that won’t fall apart when challenges arise. That said, promoting AI literacy, reskilling initiatives, and open communication should form an integral component of this exercise. This will keep everyone on board while offering experienced, more desirable results.

 

Final Thoughts

 

Today, AI isn’t just a technology in progress but a revolution. It’s a key to getting real, measurable results on a scale. However, the real challenge lies in integrating it seamlessly and responsibly into complex business processes. That’s why adhering to structured roadmaps rooted in a clear strategic vision is crucial. Doing this on your own can feel overwhelming for businesses whose primary expertise doesn’t lie in revolutionary technologies. That’s where the right AI consulting partner can step in. Turning complexity into clarity.

Author: Devansh Bansal, VP – Presales & Emerging Technology
Bio: Devansh Bansal, Vice President – Presales & Emerging Technology, with a stint of over two decades has steered fast growth and has played a key role in evolving Damco’s technology business to respond to the changes across multiple industry sectors. He is responsible for thoroughly understanding complex end-to-end customer solutions and making recommendations, estimations, and proposals. Devansh has a proven track record of creating differentiated business-driven solutions to help our clients gain a competitive advantage.

 
 



Source link

Continue Reading

Jobs & Careers

Nagaland University Brings Fractals Into Quantum Research

Published

on


Nagaland University has entered the global quantum research spotlight with a breakthrough study that brings nature’s fractals into the quantum world.

The work, led by Biplab Pal, assistant professor of physics at the university’s School of Sciences, demonstrates how naturally occurring patterns such as snowflakes, tree branches, and neural networks can be simulated at the quantum scale.

Published in the peer-reviewed journal Physica Status Solidi – Rapid Research Letters, the research could influence India’s National Quantum Mission by broadening the materials and methods used to design next-generation quantum devices.

Fractals—repeating patterns seen in coastlines, blood vessels, and lightning strikes—have long fascinated scientists and mathematicians. This study uses those self-similar structures to model how electrons behave under a magnetic field within fractal geometries. Unlike most quantum device research that relies on crystalline materials, the work shows that non-crystalline, amorphous materials could also be engineered for quantum technologies.

“This approach is unique because it moves beyond traditional crystalline systems,” Pal said. “Our findings show that amorphous materials, guided by fractal geometries, can support the development of nanoelectronic quantum devices.”

The potential applications are wide-ranging. They include molecular fractal-based nanoelectronics, improved quantum algorithms through finer control of electron states, and harnessing the Aharonov-Bohm caging effect, which traps electrons in fractal geometries for use in quantum memory and logic devices.

University officials called the study a milestone for both Nagaland University and India’s quantum research ecosystem. “Our research shows a new pathway where naturally inspired fractal geometries can be applied in quantum systems,” vice-chancellor Jagadish K Patnaik said. “This could contribute meaningfully to the development of future quantum devices and algorithms.”

With this study, Nagaland University joins a small group of Indian institutions contributing visibly to international quantum research.



Source link

Continue Reading

Jobs & Careers

Google Launches Agent Payments Protocol to Standardise AI Transactions

Published

on


Google on Wednesday announced the Agent Payments Protocol (AP2), an open standard designed for AI agents to conduct secure and verifiable payments.

The protocol, developed with more than 60 payments and technology companies, extends Google’s existing Agent2Agent (A2A) and Model Context Protocol (MCP) frameworks.

Stavan Parikh, vice president and general manager of payments at Google, said the rise of autonomous agents requires a new foundation for trust. He added that AP2 establishes the foundation for authorization, authenticity, and accountability in agent-led transactions. 

“AP2 provides a trusted foundation to fuel a new era of AI-driven commerce. It establishes the core building blocks for secure transactions, creating clear opportunities for the industry–including networks, issuers, merchants, technology providers, and end users–to innovate on adjacent areas like seamless agent authorization and decentralized identity,” Parikh said.

Unlike traditional payment systems that assume a human directly initiates a purchase, AP2 addresses the challenges of proving intent and authority when an AI acts on a user’s behalf. The framework uses cryptographically signed digital contracts called Mandates to serve as verifiable proof of a user’s instructions. These can cover both real-time transactions, where a customer is present, and delegated tasks, such as buying concert tickets automatically under pre-approved conditions.

Rao Surapaneni, vice president and general manager of business applications platform at Google Cloud, said the protocol provides secure, compliant transactions between agents and merchants while supporting multiple payment types, from cards to stablecoins.

Google said AP2 will also support cryptocurrency payments through an extension called A2A x402, developed in partnership with Coinbase, Ethereum Foundation and MetaMask. This allows agents to handle stablecoin payments within the same framework.

Industry players expressed support for the initiative. Luke Gebb, executive vice president of Amex Digital Labs, said the rise of AI commerce makes trust and accountability more important than ever, and AP2 is intended to protect customers.

Coinbase head of engineering Erik Reppel said the inclusion of x402 showed that agent-to-agent payments aren’t just an experiment anymore and are becoming part of how developers actually build.

Adyen co-chief executive Ingo Uytdehaage said the protocol creates a “common rulebook” to ensure security and interoperability across the payments ecosystem.

Backers include Mastercard, PayPal, Revolut, Salesforce, Worldpay, Accenture, Adobe, Deloitte and Dell, who said the framework could open up opportunities for secure agent-driven commerce ranging from consumer shopping to enterprise procurement.

Google has published the technical specifications and reference implementations in a public GitHub repository and invited the wider payments and technology community to contribute to its development.



Source link

Continue Reading

Trending