In this post, we are going to talk about Python dates and time modules. This module is a built-in module and no need to install it from somewhere.
Python date and time is the best option when you want to work with time like count down or run a specific task according to a given time and more.
So, let's start to learn about this module.
Get started with it
When working with a module you need to import it into the project file. We are using the import command to it. Here we can load the Date Time module like this,
import datetime
In my experience, this module helped in two main categories.
- You can get current time even with the second and microseconds!!!
- You can put any time formatting and convert it a time and date formatting like a short time, time in chars and more
How to get the current time
getting current time is quite simple and here is how to do that. We are using datetime.datetime.now() syntax to get the exact time
How to convert a Time and Date object
In the above code, I put also the seconds, but you can put just the year, month, or day. Also, you can put even the microseconds if you want
Modifiers with the Date and Time
With this module, we can get return a time and date in a few formats like '21st January of 2022', '7 Wed February' and more. We are using strftime() syntax to do that.
Note: After using strftime(), time date format is changing to a string
s = datetime.datetime(2022, 3, 2, 12, 41, 50)
writing with short version of full time
st = s.strftime("%c")
print(st)
writing digital version of time
st = s.strftime("%X")
print(st)
writing full nameof week day
st = s.strftime("%A")
print(st)
writing full name of Month
st = s.strftime("%B")
print(st)
Writing hour in Digital time
st = s.strftime("%H")
print(st)
This is I need to explain in this post. So, there are some extra modifiers like this. And I also hope to talk about them in advance tutorials. Feel free to comment if you have any questions regarding this.