How to Create a Unique Timestamp String using Current Date and Time in Batch Script
In automation and scripting, you often need to create unique identifiers for filenames, log entries, or temporary data. The most common and effective way to do this is by generating a timestamp string in a consistent format like YYYYMMDD-HHMMSS
. This format is not only unique down to the second but also allows files to be sorted chronologically simply by name. While Batch provides the %DATE%
and %TIME%
variables, they are notoriously unreliable for scripting due to their format changing based on system regional settings.
This guide will explain the pitfalls of using %DATE%
and %TIME%
and provide a robust, modern solution using the Windows Management Instrumentation Command-line (wmic
) to create a standardized, reliable timestamp string that works on any Windows machine.
The Goal: A Unique and Sortable Timestamp
Our objective is to create a string from the current date and time that can be safely used in filenames and is unique for each second. The ideal format is YYYYMMDD-HHMMSS
because:
- Uniqueness: It's highly unlikely to run a script more than once in the same second.
- Sortability: When files with this prefix are listed alphabetically (e.g., in File Explorer or with
DIR
), they will automatically be in chronological order. - Readability: It's easily human-readable.
- File System Safe: It contains no characters that are invalid in filenames (like
/
,:
,*
, etc.).
The Problem: Why %DATE%
and %TIME%
are Unreliable
The built-in %DATE%
and %TIME%
variables seem like the obvious choice, but they are a common trap for batch scripters. Their output format changes completely based on the user's Windows regional settings.
- In the US:
%DATE%
might beWed 09/20/2023
(MM/DD/YYYY format) - In Germany:
%DATE%
might beMi 20.09.2023
(DD.MM.YYYY format) - In Japan:
%DATE%
might be2023/09/20
(YYYY/MM/DD format)
A script written to parse one format (e.g., using substrings or FOR /F
with specific delimiters) will fail completely on a machine using another, making it fragile and not portable.
The Solution: The Reliable WMIC
Method
The most robust way to get date and time components in a script-friendly manner is by using wmic
. The command wmic os get LocalDateTime
returns the date and time in a fixed, standardized format, regardless of the user's regional settings.
How wmic os get LocalDateTime
Works
Command: wmic os get LocalDateTime /VALUE
Standardized Output:
LocalDateTime=20230920113055.123456+060
This format is always YYYYMMDDHHMMSS.fractionalseconds+timezoneoffset
. This is perfect for scripting because we can reliably extract the parts we need using substring operations.
The Complete, Robust Script for Timestamp Generation
This script uses the wmic
output to create a clean YYYYMMDD-HHMMSS
timestamp.
@ECHO OFF
CLS
REM --- Get the date and time components from WMIC in a fixed format ---
REM The FOR /F loop captures the output of the wmic command.
ECHO Generating reliable timestamp...
FOR /F "tokens=2 delims==" %%I IN ('wmic os get LocalDateTime /VALUE') DO SET "wmic_datetime=%%I"
REM --- Extract the parts of the string to build our timestamp ---
REM The format is always YYYYMMDDHHMMSS.xxxxxx...
SET "YYYY=%wmic_datetime:~0,4%"
SET "MM=%wmic_datetime:~4,2%"
SET "DD=%wmic_datetime:~6,2%"
SET "HH=%wmic_datetime:~8,2%"
SET "Min=%wmic_datetime:~10,2%"
SET "Sec=%wmic_datetime:~12,2%"
SET "timestamp=%YYYY%%MM%%DD%-%HH%%Min%%Sec%"
ECHO The reliable timestamp is: %timestamp%
ECHO(
REM --- Example: Create a uniquely named log file ---
SET "logFileName=MyApplicationLog_%timestamp%.log"
ECHO This is a log entry written at %TIME%. > "%logFileName%"
ECHO Log file created: %logFileName%
DIR "%logFileName%" /B
DEL "%logFileName%"
Output:
Generating reliable timestamp...
The reliable timestamp is: 20250615-183620
Log file created: MyApplicationLog_20250615-183620.log
MyApplicationLog_20250615-183620.log
Breakdown of the wmic
Script
FOR /F "tokens=2 delims==" %%I IN ('wmic ... /VALUE') DO ...
:wmic os get LocalDateTime /VALUE
: The/VALUE
switch is key, changing the output to a simpleKey=Value
format (e.g.,LocalDateTime=2023...
), which is much easier to parse than the default table format.delims==
: We tell theFOR
loop to use the equals sign (=
) as the delimiter between tokens.tokens=2
: This tells it to grab the second token, which is the actual value after the equals sign.- The result is that the
wmic_datetime
variable is reliably set to the timestamp string (e.g.,20230920113055.123456+060
).
- Substring Extraction (
%variable:~start,length%
):- We then use standard batch substring syntax to slice up the
wmic_datetime
variable into its component parts (Year, Month, Day, etc.). This works because the position of each component is fixed. - For example,
%wmic_datetime:~0,4%
gets 4 characters starting from index 0, which is always the year (YYYY
).%wmic_datetime:~4,2%
gets 2 characters starting from index 4, which is always the month (MM
).
- We then use standard batch substring syntax to slice up the
The Original (Region-Dependent) Method Explained (for context)
For educational purposes, here is a breakdown of the clever but fragile script provided in the prompt. This method should be avoided in favor of the wmic
approach.
Example:
for /f "tokens=2-8 delims=/:. " %%A in ("%date%:%time: =0%") do set "UNIQUE=%%C%%A%%B%%D%%E%%F%%G"
Assumed Input (US Format): %date%
is Thu 01/05/2006
and %time%
is 1:06:06.96
.
%time: =0%
first replaces the leading space in the time with a zero, becoming01:06:06.96
.- The combined string passed to the
FOR
loop isThu 01/05/2006:01:06:06.96
. - The
delims=/:.
option splits this string using space, forward slash, colon, and period as delimiters.
How it parses this specific string:
Token | Variable | Value from "Thu 01/05/2006:01:06:06.96" |
---|---|---|
1 | skipped | Thu |
2 | %%A | 01 (Month) |
3 | %%B | 05 (Day) |
4 | %%C | 2006 (Year) |
5 | %%D | 01 (Hour) |
6 | %%E | 06 (Minute) |
7 | %%F | 06 (Second) |
8 | %%G | 96 (Hundredths) |
The command then reassembles these into %%C%%A%%B%%D%%E%%F%%G
-> 2006010501060696
. This parsing logic will break instantly if the system's date format is different, for example DD.MM.YYYY
.
Conclusion: Why WMIC
is the Best Practice
While parsing %DATE%
and %TIME%
with FOR /F
can seem like a quick solution, it creates fragile scripts that are not portable and will fail on systems with different regional settings.
For any task that requires a reliable and universally consistent timestamp:
Always use the wmic os get LocalDateTime
method.
It is the professional standard for modern batch scripting because its output format is fixed and independent of user locale settings, making your scripts robust and dependable across different Windows machines.