Python strftime() function
Python strftime() is a built-in function that is used to convert a date and time object into a formatted string. The name of the function is short for "string format time".
The strftime() function takes two arguments. The first argument is a format string that specifies how the output string should be formatted. The second argument is a date and time object that contains the date and time that you want to convert to a string.
Syntax:
The format argument is a string that specifies the format of the output string. The object argument is optional and specifies the date and time object that you want to convert to a string. If you omit the object argument, the strftime() function will use the current date and time.
The format string can contain special codes that are replaced with the corresponding values from the date and time object. For example, the %Y code is replaced with the year of the date, while the %m code is replaced with the month of the date.
Convert a date and time object into a formatted string
Following is an example of how to use the strftime() function to convert a date and time object into a formatted string:
In the above example, first create a datetime object representing September 1st, 2021 at 12:30 PM. Then use the strftime() function to convert this datetime object to a formatted string with the format "%Y-%m-%d %H:%M:%S". This format string specifies that the year should be displayed with four digits, followed by a hyphen, then the month and day with two digits each, followed by a space, and finally the hours, minutes, and seconds with two digits each.
Finally, the output of the strftime() function is the formatted string "2021-09-01 12:30:00".
How strftime() works in Python
The strftime() function in Python works by taking a datetime object and converting it into a formatted string. The format of the string is specified using a format string that contains special codes, called format codes, that represent various parts of the datetime object.
Here's an overview of how strftime() works:- First, a datetime object is created that contains the date and time that you want to convert to a string.
- Next, the strftime() function is called on the datetime object with a format string that specifies the desired format of the output string.
- The format string contains special codes that represent various parts of the datetime object, such as the year, month, day, hour, minute, second, and so on. These format codes are replaced with the corresponding values from the datetime object to create the final formatted string.
- The strftime() function returns the formatted string, which can be used for display or further processing.
Creating a string from a timestamp using strftime
You can create a string from a timestamp using the strftime() function in Python. The strftime() function allows you to format a timestamp in a variety of ways by specifying format codes that represent various parts of the timestamp.
Following is an example of how to create a string from a timestamp using strftime():
In the above example, a timestamp value of 1645969200 is used, which corresponds to February 28th, 2022 at 12:00:00 PM UTC. The utcfromtimestamp() function is then used to convert the timestamp to a datetime object in the UTC timezone.
Finally, the strftime() function is called on the datetime object with the format string "%Y-%m-%d %H:%M:%S", which specifies that the year should be displayed with four digits, followed by a hyphen, then the month and day with two digits each, followed by a space, and finally the hours, minutes, and seconds with two digits each.
The strftime() function then replaces the format codes in the format string with the corresponding values from the datetime object to create the final formatted string "2022-02-28 12:00:00", which is then printed to the console.
strftime Format Code List
Following is a list of format codes that can be used with the strftime() method in Python to format date and time strings:
Code | Meaning |
---|---|
%a | Abbreviated weekday name (Sun, Mon, Tue, etc.) |
%A | Full weekday name (Sunday, Monday, Tuesday, etc.) |
%w | Weekday as a decimal number (0 is Sunday, 1 is Monday, etc.) |
%d | Day of the month as a zero-padded decimal number (01-31) |
%b | Abbreviated month name (Jan, Feb, Mar, etc.) |
%B | Full month name (January, February, March, etc.) |
%m | Month as a zero-padded decimal number (01-12) |
%y | Year without century as a zero-padded decimal number (00-99) |
%Y | Year with century as a decimal number |
%H | Hour (24-hour clock) as a zero-padded decimal number (00-23) |
%I | Hour (12-hour clock) as a zero-padded decimal number (01-12) |
%p | AM/PM designation for the 12-hour clock (AM or PM) |
%M | Minute as a zero-padded decimal number (00-59) |
%S | Second as a zero-padded decimal number (00-59) |
%f | Microsecond as a decimal number (000000-999999) |
%z | UTC offset in the form ±HHMM or ±HH:MM (empty string if the object is naive) |
%Z | Time zone name (empty string if the object is naive) |
%j | Day of the year as a zero-padded decimal number (001-366) |
%U | Week number of the year (Sunday as the first day of the week) as a zero-padded decimal number (00-53) |
%W | Week number of the year (Monday as the first day of the week) as a zero-padded decimal number (00-53) |
%c | Locale’s appropriate date and time representation |
%x | Locale’s appropriate date representation |
%X | Locale’s appropriate time representation |
%% | A literal '%' character |
You can use these format codes in combination with other characters and symbols to create custom date and time formats using the strftime() method in Python.
- Python print statement "Syntax Error: invalid syntax"
- Installing Python Modules with pip
- How to get current date and time in Python?
- No module named 'pip'
- How to get the length of a string in Python
- ModuleNotFoundError: No module named 'sklearn'
- ModuleNotFoundError: No module named 'cv2'
- Python was not found; run without arguments
- Attempted relative import with no known parent package
- TypeError: only integer scalar arrays can be converted to a scalar index
- A value is trying to be set on a copy of a slice from a DataFrame
- ValueError: setting an array element with a sequence
- Indentationerror: unindent does not match any outer indentation level
- Valueerror: if using all scalar values, you must pass an index
- ImportError: libGL.so.1: cannot open shared object file: No such file or directory
- Python Try Except | Exception Handling
- Custom Exceptions in Python with Examples
- Python String replace() Method
- sqrt Python | Find the Square Root in Python
- Read JSON file using Python
- Binary search in Python
- Defaultdict in Python
- Int Object is Not Iterable – Python Error
- os.path.join in Python
- TypeError: int object is not subscriptable
- Python multiline comment
- Typeerror: str object is not callable
- Python reverse List
- zip() in Python for Parallel Iteration
- Typeerror: int object is not callable
- Python List pop() Method
- Fibonacci series in Python
- Python any() function
- Python any() Vs all()
- Python pass Statement
- Python Lowercase - String lower() Method
- Modulenotfounderror: no module named istutils.cmd
- Append to dictionary in Python : Key/Value Pair
- timeit | Measure execution time of small code
- Python Decimal to Binary
- GET and POST requests using Python
- Difference between List VS Set in Python
- How to Build Word Cloud in Python?
- Binary to Decimal in Python
- Modulenotfounderror: no module named 'apt_pkg'
- Convert List to Array Python