Picture by Editor | Midjourney
Time information is omnipresent. From monetary transactions to sensor logs, there are numerous functions the place information describing time — like a date of the yr or a timestamp marking a exact prompt — pervades real-world datasets. No shock, Python comes with loads of built-in options and libraries to carry out totally different operations, preprocessing, and evaluation on information containing dates and instances. This text exhibits ten Python one-liners to deal with frequent datetime duties effectively and concisely.
Keep in mind that a few of these one-liners might require sure imports at the beginning of your code, specifically:
from datetime import datetime, date, delta
import pandas as pd
import numpy as np
1. Present Timestamp in ISO 8601 Format
As not-so-natural as it might look, the ISO 8601 normal for formatting a timestamp is extremely helpful as a result of its low ambiguity, machine-readable format, and most significantly, as a result of many fashionable APIs like GraphQL and RESTful companies. This normal may even flip your date-time information time zone-aware (did that assertion simply sound like a tongue tornado?).
This is easy methods to acquire a timestamp describing the present time in ISO 8601 format:
print(datetime.now().isoformat())
Output:
2025-05-10T13:31:13.661144
2. Parsing and Changing a String Right into a DateTime Object
This can be a very generally wanted sort of information conversion. The date datetime.strptime()
perform, which stands for “string parsed to time”, takes two arguments: the string containing the date to be transformed, and a format template to point how the parts of a full date are proven within the enter string. This helps interpret components just like the yr, month, day, hour, and so forth. accurately. The next instance parses the string “2025-05-10” right into a datetime
object related to the date: tenth of Might, 2025.
parsed_date = datetime.strptime("2025-05-10", "%Y-%m-%d")
Strive doing, for example, parsed_date.day
. You need to get 10: the day of the month within the parsed date.
3. Add X Days to a Given Date
It’s attainable so as to add (or subtract) time lapses to a given date or datetime object through the use of the timedelta
perform. This perform can, for example, take an argument to specify plenty of days, and be used to “journey in time” that variety of days based mostly on a given date, e.g., at this time’s.
That is how, for instance, we are going to transfer the present date 7 days ahead (it’s tenth of Might as of scripting this):
print(date.at this time() + timedelta(days=7))
And all of the sudden, it kind of turned Might seventeenth, 2025. Growth.
4. Calculate the Distinction in Days Between Two Dates
Take two Python date
objects representing two totally different dates, considerably distant in time. As an illustration, somebody’s birthday and the next New Yr’s Eve. To calculate what number of pure days are these two dates far aside, we will merely subtract each objects, and entry the days
property of the uncooked subtraction consequence as follows:
print((date(2025, 12, 31) - date(2025, 6, 29)).days)
The result’s a single integer worth, on this case 185 days.
5. Generate a Date Vary of 5 Consecutive Days Utilizing Pandas
Much like native Python’s vary(n)
that defines an typically iterable vary of integer numbers from 0 to n-1, the highly effective and versatile Pandas library for information evaluation, preprocessing, and wrangling, gives a perform to outline a variety of consecutive dates by way of days, ranging from a specified day. The ensuing vary might be simply put in a local Python assortment like a easy listing, as follows:
print(pd.date_range(begin="2025-01-01", durations=5).tolist())
Importantly, the ensuing components on this vary 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. Changing a Column of Strings to a datetime attribute in a dataset
This one can be Pandas-related, specifically for a dataset described by a number of attributes and contained in a DataFrame object. Assume we now have a DataFrame referred to as df that accommodates a ‘date’ attribute with strings. This very simple one-liner will mechanically rework all instance-level values beneath this attribute into datetime objects.
pd.to_datetime(df['date'])
By printing the consequence, you could get an output like this, the place the kind is certainly verified:
0 2025-01-01
1 2025-01-02
2 2025-01-03
Title: date, dtype: datetime64[ns]
7. Getting the Weekday Title (Not the Ordinal!) From a Date
This one-liner is especially helpful for constructing pleasant GUIs (Graphical Consumer Interfaces), for example, in Net-based functions. Suppose you wish to present at this time’s day of the week, however simply not the ordinal of the day from 1 to 7, however the identify of the day itself, that’s, Monday, or Tuesday, or Wednesday, and so forth. The strftime("%A")
formatting property does the trick, and this is how:
print(datetime(2025, 5, 10).strftime("%A"))
And right here I’m, writing this text for you on a beautiful, sunny Saturday afternoon. Disclaimer: I like writing 😉
8. Create an Array of Month-to-month Dates Utilizing NumPy
Suppose you’re working with time collection information recorded every day, e.g., every day temperature readings, and sooner or later you resolve to combination the information into month-to-month averages. Chances are you’ll wish to acquire an related set of month-level timestamps to correctly label your newly aggregated information in visualizations and whatnot. This is how, for example, for month-to-month “labels” from January to Might:
print(np.arange('2025-01', '2025-06', dtype="datetime64[M]"))
The consequence shall be: ['2025-01' '2025-02' '2025-03' '2025-04' '2025-05']
9. Filter DataFrame Rows by a Date Situation
Again to the state of affairs of a dataset described by a number of attributes, certainly one of which is a date attribute, we extract a row-wise portion of a DataFrame, taking these cases the place a boolean situation on the date attribute holds.
This instance selects the information cases (total rows) the place the date contained within the date is posterior to fifteenth January, 2025:
print(df[df['date'] > '2025-01-15'])
10. Get Unix Timestamp From datetime Object
In most examples, we saved it easy and regarded day-level granularity within the instance information. Let’s finalize with a way more granular and detailed datetime object with specified hour, minute, and second-level info.
This instance, wherein the enter is at this time’s date at 15:30:45 within the afternoon, obtains the Unix timestamp, a numeric illustration of a particular time limit, that’s sometimes very helpful for environment friendly storage, comparability, and synchronization of time-based information throughout totally different sorts of programs. Not fairly interpretable by us; very interpretable by machines.
print(int(datetime(2025, 5, 10, 15, 30, 45).timestamp()))
The timestamp is initially a float (within the instance, 1746891045.0), but it surely has been transformed to an integer for ease of illustration.
Iván Palomares Carrascosa is a frontrunner, author, speaker, and adviser in AI, machine studying, deep studying & LLMs. He trains and guides others in harnessing AI in the true world.