Essential Go Time and date  Edit on GitHub      File Issue

Format time like strftime

If you prefer strftime style of formatting time values (as used in Python or Ruby) or porting code that uses that style, you can use one of several libraries.

Here’s an example using github.com/jehiah/go-strftime package:

t := time.Date(2017, 9, 4, 3, 38, 45, 0, time.UTC)
fmt.Println(strftime.Format("%Y-%m-%d %H:%M:%S", t))
2017-09-04 03:38:45

Side note on package naming: since the package name is strftime, the import path / repository path should be github.com/jehiah/strftime. It’s bad style to add go or go- to repository path.

Unfortunately, when it comes to parsing things are not as good. There are two packages:

but they both are cgo-wrappers around C libraries, which makes them more finicky to build, especially on Windows.

List of strftime directives

CodeMeaningExample
%aWeekday as locale’s abbreviated name.Mon
%AWeekday as locale’s full name.Monday
%wWeekday as a decimal number, where 0 is Sunday and 6 is Saturday.1
%dDay of the month as a zero-padded decimal number.30
%-dDay of the month as a decimal number. (Platform specific)30
%bMonth as locale’s abbreviated name.Sep
%BMonth as locale’s full name.September
%mMonth as a zero-padded decimal number.09
%-mMonth as a decimal number. (Platform specific)9
%yYear without century as a zero-padded decimal number.13
%YYear with century as a decimal number.2013
%HHour (24-hour clock) as a zero-padded decimal number.07
%-HHour (24-hour clock) as a decimal number. (Platform specific)7
%IHour (12-hour clock) as a zero-padded decimal number.07
%-IHour (12-hour clock) as a decimal number. (Platform specific)7
%pLocale’s equivalent of either AM or PM.AM
%MMinute as a zero-padded decimal number.06
%-MMinute as a decimal number. (Platform specific)6
%SSecond as a zero-padded decimal number.05
%-SSecond as a decimal number. (Platform specific)5
%fMicrosecond as a decimal number, zero-padded on the left.000000
%zUTC offset in the form +HHMM or -HHMM (empty string if the the object is naive).
%ZTime zone name (empty string if the object is naive).
%jDay of the year as a zero-padded decimal number.273
%-jDay of the year as a decimal number. (Platform specific)273
%UWeek number of the year (Sunday as the first day of the week) as a zero padded decimal number. All days in a new year preceding the first Sunday are considered to be in week 0.39
%WWeek number of the year (Monday as the first day of the week) as a decimal number. All days in a new year preceding the first Monday are considered to be in week 0.39
%cLocale’s appropriate date and time representation.Mon Sep 30 07:06:05 2013
%xLocale’s appropriate date representation.09/30/13
%XLocale’s appropriate time representation.07:06:05
%%A literal ‘%’ character.%

You can also use http://www.strfti.me/ service to help you build strftime formatting strings.

  ↑ ↓ to navigate     ↵ to select     Esc to close