Python, a versatile and widely-used programming language, offers several modules to work with dates and times. Understanding how to manage date and time can be crucial for a myriad of applications, including logging, timestamping, scheduling, and more. This guide will walk you through the basics of fetching the current date and time in Python, exploring the functionality offered by the datetime and time modules.
To understand more about it, visit our in-depth Python date time tutorial.
Get Current Date & Time in Python
To get the current date and time, you can use the `datetime.now()`
function, which returns a datetime object representing the current date and time in the local timezone.
import datetime
current_datetime = datetime.datetime.now()
print(current_datetime)
The above script will output the following:
2022-12-25 18:13:13.363653
To format the date and time in a specific way, you can use the `strftime()`
method of the datetime object, which takes a format string as an argument. The format string specifies how the date and time values should be formatted.
For example, to get the current date as a string in the `YYYY-MM-DD HH:MM:SS`
format, you can use the `%Y-%m-%d %H:%M:%S`
format string:
import datetime
current_datetime = datetime.datetime.now()
current_date = current_datetime.strftime("%Y-%m-%d %H:%M:%S")
print(current_date)
The above script will output the following:
2022-12-25 18:15:03
Python `datetime`
Module Class Attributes
The datetime module in Python provides classes for working with dates, times, and timestamps. The main class is datetime, which represents a single point in time.
Here are some common attributes of the datetime class:
`year`
: the year (four digits)`month`
: the month (1-12)`day`
: the day of the month (1-31)`hour`
: the hour of the day (0-23)`minute`
: the minute of the hour (0-59)`second`
: the second of the minute (0-59)`microsecond`
: the microsecond of the second (0-999999)`tzinfo`
: an object representing the time zone
Here is an example of creating a datetime object and accessing its attributes:
from datetime import datetime
dt = datetime(2022, 12, 31, 23, 59, 59)
## Uncomment below to get the current date and time
#dt = datetime.now()
dt = datetime.now()
print(dt.year) # prints 2022
print(dt.month) # prints 12
print(dt.day) # prints 31
print(dt.hour) # prints 23
print(dt.minute) # prints 59
print(dt.second) # prints 59
print(dt.microsecond) # prints 0
print(dt.tzinfo) # prints None
Get Formated Date Time in Python
To get a formatted date and time string in Python, you can use the `strftime`
method of the `datetime`
class.
Here is an example of using `strftime`
to get a formatted date and time string:
from datetime import datetime
# Create a datetime object
dt = datetime(2022, 12, 31, 23, 59, 59)
## Uncomment below to get the current date and time
#dt = datetime.now()
# Use strftime to create a formatted string
formatted_date = dt.strftime("%Y-%m-%d %H:%M:%S")
print(formatted_date) # prints "2022-12-31 23:59:59"
The `strftime`
method takes a format string as its argument, which specifies how the date and time should be formatted. In the example above, the format string “%Y-%m-%d %H:%M:%S” specifies that the year should be formatted as a four-digit number (`%Y`
), the month as a two-digit number (`%m`
), the day as a two-digit number (`%d`
), the hour as a two-digit number (`%H`
), the minute as a two-digit number (`%M`
), and the second as a two-digit number (`%S`
).
You can use different format codes to customize the output of `strftime`
to your liking. For example, you can use `%A`
to get the full name of the day of the week, `%B`
to get the full name of the month, and `%I`
to get the hour in 12-hour format with a leading zero for single-digit hours.
Here is a few more examples of strftime format codes:
from datetime import datetime
# Create a datetime object
dt = datetime(2022, 12, 31, 23, 59, 59)
## Uncomment below to get the current date and time
#dt = datetime.now()
# Use strftime to create a formatted string
print(dt.strftime("%Y-%m-%d %H:%M:%S")) # prints 2022-12-31 23:59:59
print(dt.strftime("%Y/%m/%d")) # prints 2022/12/31
print(dt.strftime("%H:%M:%S")) # prints 23:59:59
print(dt.strftime("%I:%M:%S %p")) # prints 11:59:59 PM
print(dt.strftime("%a, %b %d, %Y")) # prints Sat, Dec 31, 2022
print(dt.strftime("%a, %b %d, %Y %H:%M:%S")) # prints Sat, Dec 31, 2022 23:59:59
print(dt.strftime("%a %b %d %H:%M:%S %Y")) # prints Sat Dec 31 23:59:59 2022
print(dt.strftime("%A, %B %d, %Y %I:%M %p")) # prints Saturday, December 31, 2022 11:59 PM"
Below is the list of directives that can be used to format date and time output in your Python script.
Directive | Meaning |
---|---|
%a | Locale’s abbreviated weekday name. |
%A | Locale’s full weekday name. |
%b | Locale’s abbreviated month name. |
%B | Locale’s full month name. |
%c | Locale’s appropriate date and time representation. |
%d | Day of the month as a decimal number [01,31]. |
%H | Hour (24-hour clock) as a decimal number [00,23]. |
%I | Hour (12-hour clock) as a decimal number [01,12]. |
%j | Day of the year as a decimal number [001,366]. |
%m | Month as a decimal number [01,12]. |
%M | Minute as a decimal number [00,59]. |
%p | Locale’s equivalent of either AM or PM. |
%S | Second as a decimal number [00,61]. |
%U | Week number of the year (Sunday as the first day of the week) as a decimal number [00,53]. All days in a new year preceding the first Sunday are considered to be in week 0. |
%w | Weekday as a decimal number [0(Sunday),6]. |
%W | Week number of the year (Monday as the first day of the week) as a decimal number [00,53]. All days in a new year preceding the first Monday are considered to be in week 0. |
%x | Locale’s appropriate date representation. |
%X | Locale’s appropriate time representation. |
%y | Year without century as a decimal number [00,99]. |
%Y | Year with century as a decimal number. |
%z | Time zone offset indicating a positive or negative time difference from UTC/GMT of the form +HHMM or -HHMM, where H represents decimal hour digits and M represents decimal minute digits [-23:59, +23:59]. |
%Z | Time zone name (no characters if no time zone exists). |
%% | A literal '%' character. |
I hope these examples have helped you understand how to get the current date and time in Python, and how to convert between timezones.
Conclusion
In summary, the datetime module is a convenient and powerful tool for working with dates, times, and timestamps in Python. You can use the datetime.now() function to get the current date and time in the local timezone, or the datetime.utcnow() function to get the current date and time in the UTC timezone. You can also use the datetime() constructor to create a datetime object for a specific date and time.
4 Comments
content is Very helpful sir !
Thnx, very helpful!
Every nicely explianed!
Thank you!