Ten Python One-Liners to Get Today’s Date as YYYY-MM-DD

5/5 - (6 votes)

Mini Project Description

I was just working on the Finxter app that involves creating a huge amount of log files (for server logs at app.finxter.com). In my Python web app, I create these log files on a daily basis containing usage reports — and I needed to rename them so that I can sort them in a folder by date.

Examples with bolded YYYY-MM-DD date formatting:

  • 'log-file-2022-12-21.dat'
  • 'log-file-2022-12-22.dat'
  • 'log-file-2022-12-23.dat'

πŸ’¬ Challenge: Specifically, I need to create the current date YYYY-MM-DD in Python!

In this short tutorial, I quickly share my code on how to do this so it may help you do the same or a similar task. Let’s get started! πŸ‘‡

Quick Solution

The datetime.date.today() function creates a datetime object with the current date that can be reformatted using the strftime('%Y-%m-%d') method call to print out the current date in a specific format (year-month-day).

Here’s an example for today:

import datetime

today = datetime.date.today()
# 2022-12-23

Or in a single line of Python code:

import datetime; print(datetime.date.today().strftime('%Y-%m-%d'))
# 2022-12-23

If you’re like me, you’re wondering how to get to this quite lengthy code snippet. Let’s break it down to further our understanding.

Here are two variants of the .today() method that can help you understand how we got there:

>>> datetime.datetime.today()
datetime.datetime(2022, 12, 23, 0, 27, 28, 712504)
>>> datetime.date.today()
datetime.date(2022, 12, 23)

Note you can also convert both the date and the datetime objects to a string using the built-in str() method:

>>> str(datetime.date.today())
>>> str(datetime.datetime.today())
'2022-12-23 00:30:04.218695'

Basically, the first line already presents an even easier solution. VoilΓ ! πŸ‘Œ

Just for fun, I came up with additional solutions—I’ll give ten different solutions next!

10 One-Liner Solutions

These are ten different ways to get today’s date in YYYY-MM-DD format in Python:

1) datetime.datetime.now().strftime("%Y-%m-%d")
2) datetime.date.today().strftime("%Y-%m-%d")
3) time.strftime("%Y-%m-%d")
4) datetime.date.today().isoformat()
5) datetime.date.today().strftime("%Y/%m/%d")
6) datetime.datetime.now().date().strftime("%Y-%m-%d")
7) datetime.datetime.now().date().isoformat()
8) datetime.datetime.now().strftime("%d-%m-%Y")
9) date.today().strftime("%Y-%m-%d")
10) datetime.date.today().strftime("%d/%m/%Y")

The output formats can vary slightly:

1) 2022-12-23
2) 2022-12-23
3) 2022-12-23
4) 2022-12-23
5) 2022/12/23
6) 2022-12-23
7) 2022-12-23
8) 23-12-2022
9) 2022-12-23
10) 23/12/2022

And, yes, I love Python one-liners! β™₯οΈπŸ‘‡

Python One-Liners Book: Master the Single Line First!

Python programmers will improve their computer science skills with these useful one-liners.

Python One-Liners

Python One-Liners will teach you how to read and write “one-liners”: concise statements of useful functionality packed into a single line of code. You’ll learn how to systematically unpack and understand any line of Python code, and write eloquent, powerfully compressed Python like an expert.

The book’s five chapters cover (1) tips and tricks, (2) regular expressions, (3) machine learning, (4) core data science topics, and (5) useful algorithms.

Detailed explanations of one-liners introduce key computer science concepts and boost your coding and analytical skills. You’ll learn about advanced Python features such as list comprehension, slicing, lambda functions, regular expressions, map and reduce functions, and slice assignments.

You’ll also learn how to:

  • Leverage data structures to solve real-world problems, like using Boolean indexing to find cities with above-average pollution
  • Use NumPy basics such as array, shape, axis, type, broadcasting, advanced indexing, slicing, sorting, searching, aggregating, and statistics
  • Calculate basic statistics of multidimensional data arrays and the K-Means algorithms for unsupervised learning
  • Create more advanced regular expressions using grouping and named groups, negative lookaheads, escaped characters, whitespaces, character sets (and negative characters sets), and greedy/nongreedy operators
  • Understand a wide range of computer science topics, including anagrams, palindromes, supersets, permutations, factorials, prime numbers, Fibonacci numbers, obfuscation, searching, and algorithmic sorting

By the end of the book, you’ll know how to write Python at its most refined, and create concise, beautiful pieces of “Python art” in merely a single line.

Get your Python One-Liners on Amazon!!

An in-depth tutorial on this topic can be found on the Finxter blog. See here:

πŸ‘‰ Recommended: How to Print Today in Python?