In this article, you will learn to get current time of your locale as well as different time zones in Python.
There are a number of ways you can take to get current time in Python.
Example 1: Current time using datetime object
from datetime import datetime
now = datetime.now[]
current_time = now.strftime["%H:%M:%S"]
print["Current Time =", current_time]
Output
Current Time = 07:41:19
In the above example, we have imported datetime
class
from the datetime module. Then, we used now[]
method to get a datetime
object containing current date and time.
Using datetime.strftime[] method, we then created a string representing current time.
If you need to create a time
object containing current time, you can do something like this.
from datetime import datetime
now = datetime.now[].time[] # time object
print["now =", now]
print["type[now] =", type[now]]
Output
now = 07:43:37.457423 type[now] =
Example 2: Current time using time module
You can also get the current time using time module.
import time
t = time.localtime[]
current_time = time.strftime["%H:%M:%S", t]
print[current_time]
Output
07:46:58
Example 3: Current time of a timezone
If you need to find current time of a certain timezone, you can use pytZ module.
from datetime import datetime
import pytz
tz_NY = pytz.timezone['America/New_York']
datetime_NY = datetime.now[tz_NY]
print["NY time:", datetime_NY.strftime["%H:%M:%S"]]
tz_London = pytz.timezone['Europe/London']
datetime_London = datetime.now[tz_London]
print["London time:", datetime_London.strftime["%H:%M:%S"]]
Output
NY time: 03:45:16 London time: 08:45:16
In this article, you will learn to get today's date and current date and time in Python. We will also format the date and time in different formats using strftime[] method.
Video: Dates and Times in Python
There are a number of ways you can take to get the current date. We will use the
date
class of the datetime module to accomplish this task.
Example 1: Python get today's date
from datetime import date
today = date.today[]
print["Today's date:", today]
Here, we imported the date
class from the datetime
module. Then, we used the date.today[]
method to get the current local date.
By the way, date.today[]
returns a date
object, which is assigned to the today variable in the above
program. Now, you can use the strftime[] method to create a string representing date in different formats.
Example 2: Current date in different formats
from datetime import date
today = date.today[]
# dd/mm/YY
d1 = today.strftime["%d/%m/%Y"]
print["d1 =", d1]
# Textual month, day and year
d2 = today.strftime["%B %d, %Y"]
print["d2 =", d2]
# mm/dd/y
d3 = today.strftime["%m/%d/%y"]
print["d3 =", d3]
# Month abbreviation, day and year
d4 = today.strftime["%b-%d-%Y"]
print["d4 =", d4]
When you run the program, the output will be something like:
d1 = 16/09/2019 d2 = September 16, 2019 d3 = 09/16/19 d4 = Sep-16-2019
If you need to get the current date and time, you can use datetime
class of the datetime
module.
Example 3: Get the current date and time
from datetime import datetime
# datetime object containing current date and time
now = datetime.now[]
print["now =", now]
# dd/mm/YY H:M:S
dt_string = now.strftime["%d/%m/%Y %H:%M:%S"]
print["date and time =", dt_string]
You will gate output like below.
now = 2021-06-25 07:58:56.550604 date and time = 25/06/2021 07:58:56
Here, we have used datetime.now[]
to get the current date and time. Then, we used strftime[]
to create a string representing date and time in another format.
How do I get the current time in Python?
The time
module
The time
module provides functions that tell us the time in "seconds since the epoch" as well as other utilities.
import time
Unix Epoch Time
This is the format you should get timestamps in for saving in databases. It is a simple floating-point number that can be converted to an integer. It is also good for arithmetic in seconds, as it represents the number of seconds since Jan 1, 1970, 00:00:00, and it is memory light relative to the other representations of time we'll be looking at next:
>>> time.time[]
1424233311.771502
This timestamp does not account for leap-seconds, so it's not linear - leap seconds are ignored. So while it is not equivalent to the international UTC standard, it is close, and therefore quite good for most cases of record-keeping.
This is not ideal for human scheduling, however. If you have a future event you wish to take place at a certain
point in time, you'll want to store that time with a string that can be parsed into a datetime
object or a serialized datetime
object [these will be described later].
time.ctime
You can also represent the current time in the way preferred by your operating system [which means it can change when you change your system preferences, so don't rely on this to be standard across all systems, as I've seen others expect]. This is typically user friendly, but doesn't typically result in strings one can sort chronologically:
>>> time.ctime[]
'Tue Feb 17 23:21:56 2015'
You can hydrate timestamps into human readable form with ctime
as well:
>>> time.ctime[1424233311.771502]
'Tue Feb 17 23:21:51 2015'
This conversion is also not good for record-keeping [except in text that will only be parsed by humans - and with improved Optical Character Recognition and Artificial Intelligence, I think the number of these cases will diminish].
datetime
module
The datetime
module is also quite useful here:
>>> import datetime
datetime.datetime.now
The datetime.now
is a
class method that returns the current time. It uses the time.localtime
without the timezone info [if not given, otherwise see timezone aware below]. It has a representation [which would allow you to recreate an equivalent object] echoed on the shell, but when printed [or coerced to a str
], it is in human readable [and nearly ISO] format, and the lexicographic sort is equivalent to the chronological sort:
>>> datetime.datetime.now[]
datetime.datetime[2015, 2, 17, 23, 43, 49, 94252]
>>> print[datetime.datetime.now[]]
2015-02-17 23:43:51.782461
datetime's utcnow
You can get a datetime object in UTC time, a global standard, by doing this:
>>> datetime.datetime.utcnow[]
datetime.datetime[2015, 2, 18, 4, 53, 28, 394163]
>>> print[datetime.datetime.utcnow[]]
2015-02-18 04:53:31.783988
UTC is a time standard that is nearly equivalent to the GMT timezone. [While GMT and UTC do not change for Daylight Savings Time, their users may switch to other timezones, like British Summer Time, during the Summer.]
datetime timezone aware
However, none of the datetime objects we've created so far can be easily converted to various timezones. We can solve that problem with the pytz
module:
>>> import pytz
>>> then = datetime.datetime.now[pytz.utc]
>>> then
datetime.datetime[2015, 2, 18, 4, 55, 58, 753949, tzinfo=]
Equivalently, in Python 3 we have
the timezone
class with a utc timezone
instance attached, which also makes the object timezone aware [but to convert to another timezone without the handy pytz
module is left as an exercise to the reader]:
>>> datetime.datetime.now[datetime.timezone.utc]
datetime.datetime[2015, 2, 18, 22, 31, 56, 564191, tzinfo=datetime.timezone.utc]
And we see we can easily convert to timezones from the original UTC object.
>>> print[then]
2015-02-18 04:55:58.753949+00:00
>>> print[then.astimezone[pytz.timezone['US/Eastern']]]
2015-02-17 23:55:58.753949-05:00
You can also make a naive datetime object aware with the pytz
timezone localize
method, or by replacing the tzinfo attribute [with replace
, this is done blindly], but these are more
last resorts than best practices:
>>> pytz.utc.localize[datetime.datetime.utcnow[]]
datetime.datetime[2015, 2, 18, 6, 6, 29, 32285, tzinfo=]
>>> datetime.datetime.utcnow[].replace[tzinfo=pytz.utc]
datetime.datetime[2015, 2, 18, 6, 9, 30, 728550, tzinfo=]
The pytz
module allows us to make our datetime
objects timezone aware and convert the times to the hundreds of timezones available in the pytz
module.
One could ostensibly serialize this object for UTC time and store that in a database, but it would require far more memory and be more prone to error than simply storing the Unix Epoch time, which I demonstrated first.
The other ways of viewing times are much more error-prone, especially when dealing with data that may come from different time zones. You want there to be no confusion as to which timezone a string or serialized datetime object was intended for.
If you're displaying the time with Python for the user, ctime
works nicely, not in a table [it doesn't typically sort well], but perhaps in a clock. However, I personally recommend, when dealing with time in Python, either using Unix time, or a timezone aware UTC datetime
object.