0

How can I covert this date format in bash

Sat Jul 17 19:07:29 2021 +0200

To

YYYY/MM/DD hh:mm:ss

2021/07/17 19:07:29

3
  • 1
    Do you have Sat Jul 17 19:07:29 2021 +0200 as the input string? Or are you getting it by running date yourself? In other words, are you more interested in converting one string to another, or are you interested in generating the correct string in the first place? Commented Jul 20, 2021 at 15:03
  • 2
    if timezone is important (different from locale), should be moved after time otherwise removed, then date -d 'Sat Jul 17 19:07:29+0200 2021' '+%Y/%m/%d %T', (or -Is instead of '+%..' for iso format). see date --help for details or man date Commented Jul 20, 2021 at 15:15
  • @omajid I'm getting date from git commit log. I need to convert the above format for a report which requires the new format. Commented Jul 20, 2021 at 17:28

1 Answer 1

1

If you are using a Unix program, you can often convince it to generate the output in the expected format instead of later trying to process it.

For example, you can do this with git log. Here's what it looks like on a repo:

$ git log --format=%ad --date='format:%Y/%m/%d %H:%M:%S' | head
2021/07/05 22:45:03
2021/07/05 22:20:49
2021/07/05 18:08:33
2021/06/09 11:18:40
2021/05/25 11:48:31
2021/05/21 18:20:40
2021/05/20 17:05:17
2021/05/20 16:53:24
2021/05/20 16:29:13
2021/05/20 16:18:24

This relies on telling git log to format entries to only show the date using --format=%ad and then specifying the format of the date you want using --date='format:%Y/%m/%d %H:%M:%S'. See man git log for more details and man date for the format spacifiers you can use with --date=format:.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.