- How to Create Filename with Date Time in Windows Batch Script
- Get Date & Time in Batch Script
- A Sample Batch Script with Date & Time
- Batch command date and time in file name
- 15 Answers 15
- how do I make the txt output from a .cmd file contain the current date and time in the filename?
- 1 Answer 1
- What is your favorite date and time format in a file name? [closed]
- Creating a file name as a timestamp in a batch job
- 17 Answers 17
How to Create Filename with Date Time in Windows Batch Script
This tutorial will help you to create files and directories with the name of current date time on Windows system. For example, you are writing a script which creates backup regularly, Now you want to organize daily backups with the current date and time name, so it will be easier to identify, which folder containers backups of which date. Go through the tutorial and understand how you can accomplish this.
Get Date & Time in Batch Script
Windows takes the date in the format like Thu 11/02/2017. Now below 3 set of commands extract the date in YYYY format, month in MM format and date in DD format and stored in CUR_YYYY, CUR_MM, and CUR_DD variables correspondingly.
Next is to parse the time which is available in 11:20:56.39 (Hours, Minutes, Seconds, and Micro Seconds) format. Now extract the hours, minutes, seconds, and microseconds and store them in variables.
Now, you have variables having current date and time in variables. You can use and create any file name as per your requirements like:
If your current date time is Nov 02, 2017 15:41:36, then the above example will create a file in the current directory with name “access_20170306-143822.log”.
A Sample Batch Script with Date & Time
The complete windows batch script will look like below. To test this create a file test.bat with the following content. Save the file and execute the script.
You will see a directory is created with name 20171102-154136 and a file create in current directory with name access_20171102-154136.log (Filename will be according to current date and time and will change during your testing)
Batch command date and time in file name
I am compressing files using WinZip on the command line. Since we archive on a daily basis, I am trying to add date and time to these files so that a new one is auto generated every time.
I use the following to generate a file name. Copy paste it to your command line and you should see a filename with a Date and Time component.
However, my issue is AM vs PM. The AM time stamp gives me time 9 (with a leading blank space) vs. 10 naturally taking up the two spaces.
I guess my issue will extend to the first nine days, first 9 months, etc. as well.
How do I fix this so that leading zeroes are included instead of leading blank spaces so I get Archive_20111011_093609.zip ?
15 Answers 15
It will give you (independent of locale settings!):
From here, it is easy:
For Logan’s request for the same outputformat for the «date-time modified» of a file:
It is a bit more complicated, because it works only with full paths, wmic expects the backslashes to be doubled and the = has to be escaped (the first one. The second one is protected by surrounding quotes).
Extract the hour, look for a leading space, if found replace with a zero;
You should search; you can simply replace all spaces with zero set hr=%hr: =0% – jeb Oct 11 ’11 at 14:16
Then use %hr% inside whatever string you are formatting to always get a two-digit hour.
(Jeb’s comment under the most popular answer worked the best for me and is the simplest. I repost it here to make it more obvious for future users.)
0,2: =0% would have been nice. :^( – Michael Feb 28 ’14 at 14:54
As Vicky already pointed out, %DATE% and %TIME% return the current date and time using the short date and time formats that are fully (endlessly) customizable.
One user may configure its system to return Fri040811 08.03PM while another user may choose 08/04/2011 20:30.
It’s a complete nightmare for a BAT programmer.
Changing the format to a firm format may fix the problem, provided you restore back the previous format before leaving the BAT file. But it may be subject to nasty race conditions and complicate recovery in cancelled BAT files.
Fortunately, there is an alternative.
You may use WMIC, instead. WMIC Path Win32_LocalTime Get Day,Hour,Minute,Month,Second,Year /Format:table returns the date and time in a invariable way. Very convenient to directly parse it with a FOR /F command.
So, putting the pieces together, try this as a starting point.
I found the best solution for me, after reading all your answers:
If AM I get 20160915_ 150101 (with a leading space and time).
If PM I get 20160915_2150101 .
21,2% set d=%d: =0% echo hello>»Archive_%d%» – Nesar Mar 12 ’18 at 17:02
You can add leading zeroes to a variable (value up to 99) like this in batch: IF 1%Var% LSS 100 SET Var=0%Var%
So you’d need to parse your date and time components out into separate variables, treat them all like this, then concatenate them back together to create the file name.
However, your underlying method for parsing date and time is dependent on system locale settings. If you’re happy for your code not to be portable to other machines, that’s probably fine, but if you expect it to work in different international contexts then you’ll need a different approach, for example by reading out the registry settings:
(That last one controls whether there is a leading zero on times, but not dates as far as I know).
This takes MB5L.txt and compresses it to ziptest20120204.zip if run on 4 Feb 2012
From the answer above, I have made a ready-to-use function.
Validated with french local settings.
As others have already pointed out, the date and time formats of %DATE% and %TIME% (as well as date /T and time /T ) are locale-dependent, so extracting the current date and time is always a nightmare, and it is impossible to get a solution that works with all possible formats since there are hardly any format limitations.
But there is another problem with a code like the following one (let us assume a date format like MM/DD/YYYY and a 12 h time format like h:mm:ss.ff ap where ap is either AM or PM and ff are fractional seconds):
Each instance of %DATE% and %TIME% returns the date or time value present at the time of its expansion, therefore the first %DATE% or %TIME% expression might return a different value than the following ones (you can prove that when echoing a long string containing a huge amount of such, preferrably %TIME% , expressions).
You could improve the aforementioned code to hold a single instance of %DATE% and %TIME% like this:
But still, the returned values in %DATE% and %TIME% could reflect different days when executed at midnight.
The only way to have the same day in %CURRDATE% and %CURRTIME% is this:
Of course the occurrence of the described problem is quite improbable, but at one point it will happen and cause strange unexplainable failures.
The described problem cannot occur with the approaches based on the wmic command as described in the answer by user Stephan and in the answer by user PA., so I strongly recommend to go for one of them. The only disadvantage of wmic is that it is way slower.
how do I make the txt output from a .cmd file contain the current date and time in the filename?
I have a script that scans computers for a certain registry entry. I want to make it to where after the scan the text file that is created, to include the date and time of day as part of the filename (date from the local machine is ok). I have found some examples that seem to do this but either I don’t understand their answer or they are not including it in the file name.
Please, if you give an answer to explain what each part is that allows the date to be in the file name. I have seen things about tokens and indices and I do not understand what those are but I am very new to scripting and am trying to learn about this.
Below is the code I have so far for my script.
As you can see I changed the actual registry key I was looking for. Honestly any command can be put there as I am focused on trying to find out how to make the text file that is being created have the correct timestamp within the file name.
Operating System: Windows XP and Windows 7 Note: Please excuse me not being able to give the exact name of the scripting language I am using as the only way I know how to refer to it is «Windows Command Line Script». I don’t even know if that is correct.
1 Answer 1
I found the answer mostly with help from a co-worker and also some with various stack overflow posts. I was concerned with not only seeing the answer but what exactly was going on with the commands.
Below sets the DateTime variable to the local date and time in yyyymmdd_hhmmss This code is correctly used being placed in your script.
Explanation: If you run the below command in cmd
you get the output of (different numbers depending on the date/time you do this):
Now we need to format this. For this purpose I only care for the date and time. The second line has the date and time in the format yyyymmddhhmmss with some extra gobbly goop. We obviously don’t want the first line and we don’t want the .702000-300.
To remove this we need to format. By using «skip=1»,you are skipping the first line. The :
#,# helps you to choose which characters to use (Don’t actually use the # character, I’m only using that as a placeholder so you know a number goes there). The first # is your starting value and the second # is the number of characters after the starting value. We want to use the first 8 characters for the date (yyymmdd) and therefore we have the starting value as 0 (the first #) and the second # as 8.
I then add the underscore and the information needed for the 6 characters for the time (hhmmss).
Within your script you can now have the code to call the DateTime variable.
Now the text file with the word hello in it will have the file name below:
Now obviously the numbers will be different depending on the time you did this.
What is your favorite date and time format in a file name? [closed]
This is a somewhat subjective question, and not very important in the big scheme of things, but something that yet annoys me regularly. There seems to be no self-evident way to put a timestamp in a file name.
Objective issue is that timestamps in file names should be sortable. But .NET sortable date formats like «s» ( «yyyy-MM-ddTHH:mm:ss» ) and «u» ( «yyyy-MM-dd HH:mm:ssZ» ) are not valid in file names because of ‘:’ characters.
Other thing is that you should easily see if universal or local time is used. Practically, users seem to prefer local time to universal time.
I have mostly ended up using ISO 8601 with basic time format:
- Local time format string «yyyy-MM-ddTHHmmsszz»
- UTC format string «yyyy-MM-ddTHHmmssZ»
In these formats my current local time would be «2009-08-08T151800+03» and UTC «2009-08-08T121800Z»
You can also autodetect the DateTime.Kind with «K» and use «yyyy-MM-ddTHHmmssK» , but then you’ll have to replace the ‘:’ characters.
Any other suggestions?
Edit: A few notes so far:
local time + time zone format «yyyy-MM-ddTHHmmsszz» is no longer sortable if multiple time zones are involved. In most cases it would make sense to drop the time zone info if it is redundant, and use UTC otherwise.
Another thing is that UTC should always be marked with ‘Z’, ‘GMT’ or ‘UTC’ to prevent guesswork and mistakes.
Julian dates and other stardates are cool because date arithmetic with the gregorian calendar is braindead.
Creating a file name as a timestamp in a batch job
We have a batch job that runs every day and copies a file to a pickup folder. I want to also take a copy of that file and drop it into an archive folder with the filename
What’s the easiest way to do this in a Windows batch job?
I’m basically looking for an equivalent of this Unix command:
17 Answers 17
But it’s locale dependent. I’m not sure if %DATE% is localized, or depends on the format specified for the short date in Windows.
Here is a locale-independent way to extract the current date from this answer, but it depends on WMIC and FOR /F :
-10,-8%.log – Eoin Campbell Jun 30 ’09 at 16:37
7,2% – opello Jun 30 ’09 at 16:45
-5,2% – MRC Oct 1 ’14 at 12:45
This worked for me and was a filename-safe solution (though it generates a MM-dd-YYYY format):
The first command takes a DATE and replaces / with — , takes the TIME and replaces : with — , and combines them into DATE@TIME format. The second set statement removes any spaces, and the third set replaces , with . and appends the .jpg extension.
The above code is used in a little script that pulls images from a security IP Camera for further processing:
For French Locale (France) ONLY, be careful because / appears in the date :
For our problem of log file, here is my proposal for French Locale ONLY: