10 Python One-Liners for Working with Dates and Times
These ten compact and pythonic shortcuts will boost your time data analysis and processing workflows. See how and why.

Image by Editor | Midjourney
Time data is omnipresent. From financial transactions to sensor logs, there are countless applications where data describing time — like a date of the year or a timestamp marking a precise instant — pervades real-world datasets. No surprise, Python comes with plenty of built-in features and libraries to perform different operations, preprocessing, and analysis on data containing dates and times. This article shows ten Python one-liners to handle common datetime tasks efficiently and concisely.
Bear in mind that some of these one-liners may require certain imports at the start of your code, namely:
from datetime import datetime, date, delta
import pandas as pd
import numpy as np
1. Current Timestamp in ISO 8601 Format
As not-so-natural as it may look, the ISO 8601 standard for formatting a timestamp is incredibly useful due to its low ambiguity, machine-readable format, and most importantly, because many modern APIs like GraphQL and RESTful services. This standard can even turn your date-time data time zone-aware (did that statement just sound like a tongue twister?).
Here's how to obtain a timestamp describing the current time in ISO 8601 format:
print(datetime.now().isoformat())
Output:
2025-05-10T13:31:13.661144
2. Parsing and Converting a String Into a DateTime Object
This is a very commonly needed kind of data conversion. The date datetime.strptime() function, which stands for "string parsed to time", takes two arguments: the string containing the date to be converted, and a format template to indicate how the components of a full date are shown in the input string. This helps interpret elements like the year, month, day, hour, etc. correctly. The following example parses the string "2025-05-10" into a datetime object associated with the date: 10th of May, 2025.
parsed_date = datetime.strptime("2025-05-10", "%Y-%m-%d")
Try doing, for instance, parsed_date.day. You should get 10: the day of the month in the parsed date.
3. Add X Days to a Given Date
It is possible to add (or subtract) time lapses to a given date or datetime object by using the timedelta function. This function can, for instance, take an argument to specify a number of days, and be used to "travel in time" that number of days based on a given date, e.g., today's.
This is how, for example, we will move the current date 7 days forward (it is 10th of May as of writing this):
print(date.today() + timedelta(days=7))
And suddenly, it sort of became May 17th, 2025. Boom.
4. Calculate the Difference in Days Between Two Dates
Take two Python date objects representing two different dates, somewhat distant in time. For instance, someone's birthday and the subsequent New Year's Eve. To calculate how many natural days are these two dates far apart, we can simply subtract both objects, and access the days property of the raw subtraction result as follows:
print((date(2025, 12, 31) - date(2025, 6, 29)).days)
The result is a single integer value, in this case 185 days.
5. Generate a Date Range of 5 Consecutive Days Using Pandas
Similar to native Python's range(n) that defines an often iterable range of integer numbers from 0 to n-1, the powerful and versatile Pandas library for data analysis, preprocessing, and wrangling, provides a function to define a range of consecutive dates in terms of days, starting from a specified day. The resulting range can be easily put in a native Python collection like a simple list, as follows:
print(pd.date_range(start="2025-01-01", periods=5).tolist())
Importantly, the resulting elements in this range are modeled as Pandas' Timestamp objects:
[Timestamp('2025-01-01 00:00:00'), Timestamp('2025-01-02 00:00:00'), Timestamp('2025-01-03 00:00:00'), Timestamp('2025-01-04 00:00:00'), Timestamp('2025-01-05 00:00:00')]
6. Converting a Column of Strings to a datetime attribute in a dataset
This one is also Pandas-related, namely for a dataset described by multiple attributes and contained in a DataFrame object. Assume we have a DataFrame called df that contains a 'date' attribute with strings. This extremely simple one-liner will automatically transform all instance-level values under this attribute into datetime objects.
pd.to_datetime(df['date'])
By printing the result, you may get an output like this, where the type is indeed verified:
0 2025-01-01
1 2025-01-02
2 2025-01-03
Name: date, dtype: datetime64[ns]
7. Getting the Weekday Name (Not the Ordinal!) From a Date
This one-liner is particularly useful for building friendly GUIs (Graphical User Interfaces), for instance, in Web-based applications. Suppose you want to show today's day of the week, but just not the ordinal of the day from 1 to 7, but the name of the day itself, that is, Monday, or Tuesday, or Wednesday, and so on. The strftime("%A") formatting property does the trick, and here's how:
print(datetime(2025, 5, 10).strftime("%A"))
And here I am, writing this article for you on a lovely, sunny Saturday afternoon. Disclaimer: I like writing ;)
8. Create an Array of Monthly Dates Using NumPy
Suppose you are working with time series data recorded daily, e.g., daily temperature readings, and at some point you decide to aggregate the data into monthly averages. You may want to obtain an associated set of month-level timestamps to properly label your newly aggregated data in visualizations and whatnot. Here's how, for instance, for monthly "labels" from January to May:
print(np.arange('2025-01', '2025-06', dtype='datetime64[M]'))
The result will be: ['2025-01' '2025-02' '2025-03' '2025-04' '2025-05']
9. Filter DataFrame Rows by a Date Condition
Back to the scenario of a dataset described by multiple attributes, one of which is a date attribute, we extract a row-wise portion of a DataFrame, taking those instances where a boolean condition on the date attribute holds.
This example selects the data instances (entire rows) where the date contained in the date is posterior to 15th January, 2025:
print(df[df['date'] > '2025-01-15'])
10. Get Unix Timestamp From datetime Object
In most examples, we kept it simple and considered day-level granularity in the example data. Let's finalize with a much more granular and detailed datetime object with specified hour, minute, and second-level information.
This example, in which the input is today's date at 15:30:45 in the afternoon, obtains the Unix timestamp, a numeric representation of a specific point in time, that is typically very useful for efficient storage, comparison, and synchronization of time-based data across different kinds of systems. Not quite interpretable by us; very interpretable by machines.
print(int(datetime(2025, 5, 10, 15, 30, 45).timestamp()))
The timestamp is originally a float (in the example, 1746891045.0), but it has been converted to an integer for ease of representation.
Iván Palomares Carrascosa is a leader, writer, speaker, and adviser in AI, machine learning, deep learning & LLMs. He trains and guides others in harnessing AI in the real world.