Formatting time in linux

Custom format for time command

I’d like to use the time command in a bash script to calculate the elapsed time of the script and write that to a log file. I only need the real time, not the user and sys. Also need it in a decent format. e.g 00:00:00:00 (not like the standard output). I appreciate any advice. The expected format supposed to be 00:00:00.0000 (milliseconds) [hours]:[minutes]:[seconds].[milliseconds] I’ve already 3 scripts. I saw an example like this:

But I only need the real time, not the user and sys. Also need it in a decent format. e.g 00:00:00:00 (not like the standard output). In other words, I’d like to know how to turn the time output into something easier to process.

New bash versions (>= 4.2) do offer a printf syntaxe for this: printf -v TimeStamp «%(%s)T» -1 and printf «%(%a %d %b %Y %T)T\n» $TimeStamp values could be -1 : now, -2 : Start of bash session, Integer : Unix timestamp

6 Answers 6

You could use the date command to get the current time before and after performing the work to be timed and calculate the difference like this:

#!/bin/bash # Get time as a UNIX timestamp (seconds elapsed since Jan 1, 1970 0:00 UTC) T="$(date +%s)" # Do some work here sleep 2 T="$(($(date +%s)-T))" echo "Time in seconds: $" printf "Pretty format: %02d:%02d:%02d:%02d\n" "$((T/86400))" "$((T/3600%24))" "$((T/60%60))" "$((T%60))"" 

Notes: $((. )) can be used for basic arithmetic in bash – caution: do not put spaces before a minus as this might be interpreted as a command-line option.

EDIT:
Additionally, you may want to take a look at sed to search and extract substrings from the output generated by time.

Example for timing with milliseconds (actually nanoseconds but truncated to milliseconds here). Your version of date has to support the %N format and bash should support large numbers.

# UNIX timestamp concatenated with nanoseconds T="$(date +%s%N)" # Do some work here sleep 2 # Time interval in nanoseconds T="$(($(date +%s%N)-T))" # Seconds S="$((T/1000000000))" # Milliseconds M="$((T/1000000))" echo "Time in nanoseconds: $" printf "Pretty format: %02d:%02d:%02d:%02d.%03d\n" "$((S/86400))" "$((S/3600%24))" "$((S/60%60))" "$((S%60))" "$" 

DISCLAIMER:
My original version said

but this was edited out because it apparently did not work for some people whereas the new version reportedly did. I did not approve of this because I think that you have to use the remainder only but was outvoted.
Choose whatever fits you.

Источник

Date Command in Linux: How to Set, Change, Format and Display Date

Linux date command displays and sets the system date and time. This command also allows users to print the time in different formats and calculate future and past dates.

Читайте также:  Просмотр всех файлов линукс

Read on to learn how to use the date command in Linux.

How to use Linux date command

  • A system running Linux
  • A user account with root privileges
  • Access to a terminal window/command line

Linux date Command Syntax

The syntax for the date command is:

How to Use date Command in Linux

To show the current system time and date, type in the date command:

Date command in linux

The output displays the day of the week, day of the month, month, year, current time, and time zone. By default, the date command is set to the time zone of the operating system.

The -d option allows users to operate on a specific date. For example, we can type in the following command:

See an older date

You can use the —date command to display the given date string in the format of a date. This command does not affect the system’s actual date and time values, and it only prints the requested date. For example:

Pull a date from a string

Note: Learn how can you create a script using the printf command to display the current date.

Linux date Command Format Options

To format the date command’s output, you can use control characters preceded by a + sign. Format controls begin with the % symbol and are substituted by their current values.

Here, the %Y character is replaced with the current year, %m with month, and %d with the day of the month:

date +"Year: %Y, Month: %m, Day: %d"

Format the current date

Here are another two formatting examples:

Another date format example

date +"Week number: %V Year: %y"

Another formatting example

These are the most common formatting characters for the date command:

    • %D – Display date as mm/dd/yy
    • %Y – Year (e.g., 2020)
    • %m – Month (01-12)
    • %B – Long month name (e.g., November)
    • %b – Short month name (e.g., Nov)
    • %d – Day of month (e.g., 01)
    • %j – Day of year (001-366)
    • %u – Day of week (1-7)
    • %A – Full weekday name (e.g., Friday)
    • %a – Short weekday name (e.g., Fri)
    • %H – Hour (00-23)
    • %I – Hour (01-12)
    • %M – Minute (00-59)
    • %S – Second (00-60)

    To see all formatting options, run date —help or the man command man date in your terminal.

    Set or Change Date in Linux

    To change the system clock manually, use the set command. For example, to set the date and time to 5:30 PM, May 13, 2010, type:

    Manual time set in Linux

    Most Linux distributions have the system clock synchronized using the ntp or the systemd-timesyncd services, so be careful when the setting the clock manually.

    Display Past Dates

    Use the —date option to display past dates in Linux. The date command accepts values such as «tomorrow» , «Friday» , «last Friday» , «next Friday» , «next week» , and similar. So, use the following strings to print past dates::

    Format to

    Yesterday

    Time ten seconds ago format in linux

    Display Future Dates

    The —date option can also display future dates. Like with past dates, you can type in strings to print upcoming dates:

    Date next monday format in linux

    Date four days from now format in linux

    Tomorrow

    Display the Date String at Line of File

    The —file option prints the date string present at each line of the file. Unlike the —date option, —file can present multiple date strings at each line.

    This is the syntax for the —file command:

    Here we use the cat command to add dates to a file and then print them with the date command:

    Display dates at each file line in linux

    Display Last Modified Timestamp of a Date File

    When you use the -r option, the date command prints the last modification time of a file. For example, the following command prints the last time the hosts file was changed:

    The last date the file was modified in linux

    Override a Time Zone

    By default, the date command uses the time zone defined in /etc/localtime . To use a different time zone in the environment, set the TZ variable to the desired time zone.

    For example, to switch to New York time, enter:

    Switch to New York time zone in Linux

    Type in the date command to return the system to its default time zone. To see all available time zones, use the timedatectl list-timezones command.

    The date command can also show the local time for a different time zone. For example, to display the local time for 4:30 PM next Monday on the Australian east coast, type:

    date -d 'TZ="Australia/Sydney" 04:30 next Monday'

    Switch to South Australian time in Linux

    Use date with Other Commands

    You can use the date command to create file names that contain the current time and date. The input below creates a backup MySQL file in the format of the current date:

    mysqldump database_name > database_name-$(date +%Y%m%d).sql

    Another common use of the date command is in shell scripts. Below we assign the output of date to the date_now variable:

    Echo the date now variable

    Use Unix Epoch Time (Epoch Converter)

    You can use the date command as an Epoch converter. Epoch, or Unix timestamps, is the number of seconds that have passed since January 1, 1970, at 00:00:00 UTC.

    To show the number of seconds from the epoch to the current day, use the %s format control:

    Epoch seconds in linux

    To see how many seconds passed from epoch to a specific date, enter:

    Epoch seconds from a specific date in Linux

    You now have a good understanding of how to use the date command in Linux. If you are interested in more date/time configuration options for Linux, read How to Set or Change Timezone/Date/Time on Ubuntu.

    Источник

    Formatting tricks for the Linux date command

    The Linux date command is simple, yet powerful. This article shows you how to unleash the power of the date command.

    Magic trick with Ace of Spades

    The date command is simple. However, it has several useful options that enhance it. It’s also capable of giving you practical information about past or future dates. This article shows you some of the format controls to manipulate the date command’s output. At the end of the article, I offer some practical suggestions about how you can use this command in conjunction with common tasks.

    Basic syntax for date

    The most basic syntax for the date command is simply to type in the command with no options and no format controls. Here is an example of the command and its resulting output:

    date command with output displaying day, month, day of the month, hour:minute:second, time zone, and year

    One modification for the date command is the -u option. This option converts the output to Coordinated Universal Time (UTC). Here is an example:

    date command output after using the -u option, displaying UTC time information.

    Format controls

    The real customization of the date command occurs when you start adding format controls. The controls can order output fields, manage abbreviations, set the format of the date on the screen or in a file, etc. At the end of the article, I show some examples of how you might use date , and you’ll see how controlling the format is useful.

    Basic format control syntax

    Use one or more format controls to display information. Here is the general syntax:

    Let’s look at a few examples.

    Label the output fields

    If you want the output labeled, you can use this format:

    Output of: date +

    Change the order of the fields

    You can alter the order in which the fields are displayed. This is one of the most useful customizations of date because it allows you to display the output in whatever format is most useful or familiar to you. Here is one way to do it:

    Output of date +

    Output from the date +

    This example reverses the results:

    Output of the date +

    Use dashes, slashes, or spaces between the fields

    Maybe you need to format the date output to meet particular standards, such as date information separated by dash, slash, or space characters. Here are a couple of different examples:

    Output of date with fields separated by - characters and then in the second example by / characters

    Linux security

    Display information from outside my current locale or time zone

    It’s embarrassing to say, but for whatever reason, time zones completely mess with my mind. They always have and they probably always will. That’s why I was excited to discover that the date command can save me from having to visualize the sun’s position over a particular geographical location to figure out the appropriate time zone.

    First, you must know the name of the time zone you wish to check. You can use the timedatectl list-timezones command to display this information.

    Next, combine the TZ value with the date command to display the time zone’s time and date information. To show the time on the east coast of the US, run this command:

    Output of the TZ=

    Run the following command to display the time in Tokyo:

    Output of the TZ=

    Display future time/date

    What if you’re coordinating a meeting with someone on the east coast of the US, and you want to confirm or display a particular future time? You can use the date command to display that information.

    First, you could display the date and time information for next Friday:

    Output of date --date=

    Here is an example that displays the local time for 10 AM next Friday on the east coast of the US:

    Output of the date command displaying a future time and date in New York

    Display past dates

    You can also use date to display past information.

    Output from the date --date=

    This example shows time and date information from 15 days ago:

    Output from the date --date=

    Practical application

    It’s one thing to know these tricks when using the date command, but it’s another to understand how to apply them. Here are a few straightforward scenarios to get you thinking about your own tasks where date might be useful.

    Redirect

    You can redirect the date command into a text file. You can use any of the format controls above to customize the output. For example, what if you are conducting a very simple server documentation project? You might use the following commands:

    Output from a series of system inventory commands, including date.

    Set a date alias

    Do you prefer the date and time to be displayed in a specific format different from the default? Set an alias for date that shows the information the way you like it. You can do this in your ~/.bashrc file.

    Alias of a formatted date command in ~/.bashrcOutput of the

    Set the format as a variable

    You can also set the date configuration as a variable on your system.

    Displays content of a script declaring a variable

    Create a template file, then copy/paste the content into scripts depending on the format desired

    Perhaps you create or manage various scripts, and the date output is needed in several of them. However, the date format must be different in each script. You could create a master template file that stores the required formats and then copy/paste the appropriate template into your new scripts.

    Template displaying 3 formatted date commands for use in scripts

    Wrap up

    Like many things in Linux, the date command is simple but also very flexible. You can control the format of the data that returned to you, ensuring you get the information you need as efficiently as possible. How have you used the date command to make your life easier?

    Источник

Оцените статью
Adblock
detector