user46646
user46646

Reputation: 159441

How do I get the current time in Python?

How do I get the current time in Python?

Upvotes: 3946

Views: 4630365

Answers (30)

Abduvahob Kaxarov
Abduvahob Kaxarov

Reputation: 247

If you using it for django datetime sometimes won't work on server so I recommend using timezone

But for use django timezone you should set your country timezone code in your settings.py

TIME_ZONE = 'Asia/Tashkent'

Then you can use it

from django.utils import timezone

timezone.now() // for date time

timezone.now().year // for yaer

timezone.now().month // for month

timezone.now().day // for day 

timezone.now().date // for date

timezone.now().hour // for hour

timezone.now().weekday // for minute

or if you want use on python

import time

time.strftime('%X') // '13:12:47'

time.strftime('%x') // '01/20/22'

time.strftime('%d') // '20' day

time.strftime('%m') // '01' month

time.strftime('%y') // '20' year

time.strftime('%H') // '01' hour

time.strftime('%M') // '01' minute

time.strftime('%m') // '01' second

Upvotes: 5

Harsh
Harsh

Reputation: 191

import datetime

print('date='+datetime.datetime.now().__str__().split(' ')[0]+' '+'time='+datetime.datetime.now().__str__().split(' ')[1]

Since Qt is used extensively,

from PyQt5 import QDateTime
print(QDateTime.currentDateTime().__str__().split('(')[1].rstrip(')'))

Upvotes: 4

Muhammad Ali
Muhammad Ali

Reputation: 1330

There are a lot of methods for getting current time in python in different formats.

I have listed all, you can use them according to your needs.

By Datetime method

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

Current time using time module

import time

t = time.localtime()
current_time = time.strftime("%H:%M:%S", t)
print(current_time)

Tue Jul 12 10:37:46 2022

Want time of a certain timezone? try this.

from datetime import datetime
import pytz

# Get the timezone object for New York
tz_NY = pytz.timezone('America/New_York') 

# Get the current time in New York
datetime_NY = datetime.now(tz_NY)

# Format the time as a string and print it
print("NY time:", datetime_NY.strftime("%H:%M:%S"))

# Get the timezone object for London
tz_London = pytz.timezone('Europe/London')

# Get the current time in London
datetime_London = datetime.now(tz_London)

# Format the time as a string and print it
print("London time:", datetime_London.strftime("%H:%M:%S"))

NY time: 03:45:16

London time: 08:45:16

UTC(Coordinated Universal Time)

from datetime import datetime

print("UTC Time: ", datetime.utcnow())

UTC Time: 2022-06-20 11:10:18.289111

ISO Format

from datetime import datetime as dt

x = dt.now().isoformat()
print('Current ISO:', x)

Current ISO: 2022-06-20T17:03:23.299672

EPOCH time

import time

print("Epoch Time is : ", int(time.time()))

Epoch Time is : 1655723915

Getting Current GMT (Green Mean Time) using time

import time

# current GMT Time
gmt_time = time.gmtime(time.time())

print('Current GMT Time:\n', gmt_time)

Current GMT Time: time.struct_time(tm_year=2022, tm_mon=6, tm_mday=20, tm_hour=11, tm_min=24, tm_sec=59, tm_wday=0, tm_yday=171, tm_isdst=0)

FYI

  • time is more accurate than datetime because if you don’t want ambiguity with daylight savings time (DST), use time.
  • datetime has more built-in objects you can work with but has limited support for time zones.
  • UTC: is a helpful reference when working with applications that require a global user to log events.
  • EPOCH: For Operating systems and file formats.
  • ISO format: to avoid any problems in communicating the date and time related data all around the world.
  • Greenmeantime: The USA had already decided to base its own national time zone scheme on Greenwich and countries like Ireland, Canada also consider their reference as GMT.

Upvotes: 15

Olney1
Olney1

Reputation: 762

There are so many complex solutions here it could be confusing for a beginner. I find this is the most simple solution to the question - as it just returns the current time as asked (no frills):

import datetime

time_now = datetime.datetime.now()

display_time = time_now.strftime("%H:%M")
print(display_time)

If you wanted more detail back than just the current time, you can do what some others have suggested here:

import datetime

time_now = datetime.datetime.now()
print(time_now)

Although this approach is shorter to write, it returns the current date and milliseconds as well, which may not be required when simply looking to return the current time.

Upvotes: 3

prudhvi Indana
prudhvi Indana

Reputation: 829

Using pandas to get the current time, kind of overkilling the problem at hand:

import pandas as pd
print(pd.datetime.now())
print(pd.datetime.now().date())
print(pd.datetime.now().year)
print(pd.datetime.now().month)
print(pd.datetime.now().day)
print(pd.datetime.now().hour)
print(pd.datetime.now().minute)
print(pd.datetime.now().second)
print(pd.datetime.now().microsecond)

Output:

2017-09-22 12:44:56.092642
2017-09-22
2017
9
22
12
44
56
92693

Upvotes: 45

Brian
Brian

Reputation: 13593

If you need a time-zone aware solution. I like to use the following 5 lines of code to get the current time.

from datetime import datetime
import pytz

# Specify the timezone
my_time_zone = pytz.timezone('Asia/Singapore')

# Pass the timezone to datetime.now() function
my_time = datetime.now(my_time_zone)

# Convert the type `my_time` to string with '%Y-%m-%d %H:%M:%S' format.
current_time = my_time.strftime('%Y-%m-%d %H:%M:%S') # current_time would be something like 2023-01-23 14:09:48

You can find the list of all timezones using pytz.all_timezones.

The meaning of the symbols in %Y-%m-%d %H:%M:%S can be found in geeksforgeeks Python strftime() function

Upvotes: -1

陳遠謀
陳遠謀

Reputation: 29

import datetime
import pytz # for timezone()
import time

current_time1 = datetime.datetime.now()
current_time2 = datetime.datetime.now(pytz.timezone('Asia/Taipei'))
current_time3 = datetime.datetime.utcnow()
current_time4 = datetime.datetime.now().isoformat()
current_time5 = time.gmtime(time.time())

print("datetime.datetime.now():", current_time1)
print("datetime.datetime.now(pytz.timezone('Asia/Taipei')):", current_time2)
print("datetime.utcnow():", current_time3)
print("datetime.datetime.now().isoformat():", current_time4)
print('time.gmtime(time.time()): ', current_time5)

Upvotes: -1

rachwa
rachwa

Reputation: 2310

If you use pandas a lot you can use Timestamp, which is the equivalent of Python’s Datetime:

In [1]: import pandas as pd

In [2]: pd.Timestamp.now()
Out[2]: Timestamp('2022-06-21 21:52:50.568788')

And just the time:

In [3]: pd.Timestamp.now().strftime("%H:%M:%S")
Out[3]: '21:53:01'

Upvotes: 4

ParaMeterz
ParaMeterz

Reputation: 9907

from datetime import datetime
datetime.now().strftime('%Y-%m-%d %H:%M:%S')

Example output: '2013-09-18 11:16:32'

See list of strftime directives.

Upvotes: 884

Harley Holcombe
Harley Holcombe

Reputation: 182008

Use datetime:

>>> import datetime
>>> now = datetime.datetime.now()
>>> now
datetime.datetime(2009, 1, 6, 15, 8, 24, 78915)
>>> print(now)
2009-01-06 15:08:24.789150

For just the clock time without the date:

>>> now.time()
datetime.time(15, 8, 24, 78915)
>>> print(now.time())
15:08:24.789150

To save typing, you can import the datetime object from the datetime module:

>>> from datetime import datetime

Then remove the prefix datetime. from all of the above.

Upvotes: 3987

Sean James
Sean James

Reputation: 12359

Use time.strftime():

>>> from time import gmtime, strftime
>>> strftime("%Y-%m-%d %H:%M:%S", gmtime())
'2009-01-05 22:14:39'

Upvotes: 1230

Faraaz Kurawle
Faraaz Kurawle

Reputation: 1162

Here's the code which will only show time according to your question:

 from datetime import datetime
 time= datetime.now()
 b = time.strftime("%H:%M:%S")
 print(b)
  • Used datetime.now() to get the current date and time.
  • Then used .strftime to get desired value i.e time only.

strftime is used to retrieve the desired output or to change the default format according to our need.

Upvotes: 0

Kofi
Kofi

Reputation: 1314

Attributes of now() can be used to get the current time in python:

# importing datetime module for now()
import datetime
    
# using now() to get current time
current_time = datetime.datetime.now()
    
# Printing attributes of now().
print ("The attributes of now() are : ")
    
print ("Year : ", end = "")
print (current_time.year)
    
print ("Month : ", end = "")
print (current_time.month)
    
print ("Day : ", end = "")
print (current_time.day)
    
print ("Hour : ", end = "")
print (current_time.hour)
    
print ("Minute : ", end = "")
print (current_time.minute)
    
print ("Second : ", end = "")
print (current_time.second)
    
print ("Microsecond : ", end = "")
print (current_time.microsecond)

Upvotes: 2

Matei Piele
Matei Piele

Reputation: 620

Gets the current time and converts it to string:

from datetime import datetime
datetime.now().strftime('%Y-%m-%d %H:%M:%S')

Upvotes: -1

Sankar guru
Sankar guru

Reputation: 1015

Use this method for UTC DateTime, local Date-Time, and convert am and pm

import pytz
from datetime import datetime

#UTC Time
print("UTC Date and time")
epoch: datetime =datetime.now().replace(tzinfo=pytz.utc)
print(epoch)

#local date and time
print("Local Date and time")
today = datetime.now()
local_time = today.strftime("%Y-%M-%d:%H:%M:%S")
print(local_time)

#convert time to AM PM format
print("Date and time AM and PM")
now = today.strftime("%Y-%M-%d:%I:%M %p")
print(now)

Upvotes: -1

RITIK KUMAR
RITIK KUMAR

Reputation: 137

try this one:-

from datetime import datetime

now = datetime.now()

current_time = now.strftime("%H:%M:%S")
print("Current Time =", current_time)

Upvotes: 11

y.selivonchyk
y.selivonchyk

Reputation: 9900

To get exactly 3 decimal points for milliseconds 11:34:23.751 run this:

def get_time_str(decimal_points=3):
        return time.strftime("%H:%M:%S", time.localtime()) + '.%d' % (time.time() % 1 * 10**decimal_points)

More context:

I want to get the time with milliseconds. A simple way to get them:

import time, datetime

print(datetime.datetime.now().time())                         # 11:20:08.272239

# Or in a more complicated way
print(datetime.datetime.now().time().isoformat())             # 11:20:08.272239
print(datetime.datetime.now().time().strftime('%H:%M:%S.%f')) # 11:20:08.272239

# But do not use this:
print(time.strftime("%H:%M:%S.%f", time.localtime()), str)    # 11:20:08.%f

But I want only milliseconds, right? The shortest way to get them:

import time

time.strftime("%H:%M:%S", time.localtime()) + '.%d' % (time.time() % 1 * 1000)
# 11:34:23.751

Add or remove zeroes from the last multiplication to adjust number of decimal points, or just:

def get_time_str(decimal_points=3):
    return time.strftime("%H:%M:%S", time.localtime()) + '.%d' % (time.time() % 1 * 10**decimal_points)

Upvotes: 20

Tom
Tom

Reputation: 937

You can use the time module:

>>> import time
>>> print(time.strftime("%d/%m/%Y"))
06/02/2015

The use of the capital Y gives the full year, and using y would give 06/02/15.

You could also use the following code to give a more lengthy time:

>>> time.strftime("%a, %d %b %Y %H:%M:%S")
'Fri, 06 Feb 2015 17:45:09'

Upvotes: 52

Aaron Hall
Aaron Hall

Reputation: 395443

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=<UTC>)

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=<UTC>)
>>> datetime.datetime.utcnow().replace(tzinfo=pytz.utc)
datetime.datetime(2015, 2, 18, 6, 9, 30, 728550, tzinfo=<UTC>)

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.

Upvotes: 548

Umutambyi Gad
Umutambyi Gad

Reputation: 4101

You can try the following

import datetime

now = datetime.datetime.now()
print(now)

or

import datetime

now = datetime.datetime.now()
print(now.strftime("%Y-%b-%d, %A %I:%M:%S"))

Upvotes: 18

Tom Carrick
Tom Carrick

Reputation: 6616

From Python 3.9, the zoneinfo module can be used for getting timezones rather than using a third party library.

To get the current time in a particular timezone:

from datetime import datetime
from zoneinfo import ZoneInfo

datetime.now(tz=ZoneInfo("Europe/Amsterdam"))

Upvotes: 4

James McGuigan
James McGuigan

Reputation: 8106

If you want the time for purpose of timing function calls, then you want time.perf_counter().

start_time = time.perf_counter()
expensive_function()
time_taken = time.perf_counter() - start_time
print(f'expensive_function() took {round(time_taken,2)}s')

time.perf_counter() → float

Return the value (in fractional seconds) of a performance counter, i.e. a clock with the highest available resolution to measure a short duration. It does include time elapsed during sleep and is system-wide. The reference point of the returned value is undefined, so that only the difference between the results of consecutive calls is valid.

New in version 3.3.


time.perf_counter_ns() → int

Similar to perf_counter(), but return time as nanoseconds.

New in version 3.7.

Upvotes: 2

Ransaka Ravihara
Ransaka Ravihara

Reputation: 1994

we can accomplish that Using datetime module

>>> from datetime import datetime
>>> now = datetime.now() #get a datetime object containing current date and time
>>> current_time = now.strftime("%H:%M:%S") #created a string representing current time
>>> print("Current Time =", current_time)
Current Time = 17:56:54

In addition, we can get the current time of time zome using pytZ module.

>>> from pytz import timezone
>>> import pytz
>>> eastern = timezone('US/Eastern')
>>> eastern.zone
'US/Eastern'
>>> amsterdam = timezone('Europe/Amsterdam')
>>> datetime_eu = datetime.now(amsterdam)
>>> print("Europe time::", datetime_eu.strftime("%H:%M:%S"))
Europe time:: 14:45:31

Upvotes: 4

Lucas Urban
Lucas Urban

Reputation: 655

The time module can import all sorts of time stuff, inculduing sleep and other types of stuff including - the current time type

import time
time.strftime("%T", time.localtime())

The output should look like this

05:46:33
11:22:56
13:44:55
22:33:44
00:00:00

Upvotes: 4

Littin Rajan
Littin Rajan

Reputation: 897

Method1: Getting Current Date and Time from system datetime

The datetime module supplies classes for manipulating dates and times.

Code

from datetime import datetime,date

print("Date: "+str(date.today().year)+"-"+str(date.today().month)+"-"+str(date.today().day))
print("Year: "+str(date.today().year))
print("Month: "+str(date.today().month))
print("Day: "+str(date.today().day)+"\n")

print("Time: "+str(datetime.today().hour)+":"+str(datetime.today().minute)+":"+str(datetime.today().second))
print("Hour: "+str(datetime.today().hour))
print("Minute: "+str(datetime.today().minute))
print("Second: "+str(datetime.today().second))
print("MilliSecond: "+str(datetime.today().microsecond))

Output will be like

Date: 2020-4-18
Year: 2020
Month: 4
Day: 18

Time: 19:30:5
Hour: 19
Minute: 30
Second: 5
MilliSecond: 836071

Method2: Getting Current Date and Time if Network is available

urllib package helps us to handle the url's that means webpages. Here we collects data from the webpage http://just-the-time.appspot.com/ and parses dateime from the webpage using the package dateparser.

Code

from urllib.request import urlopen
import dateparser

time_url = urlopen(u'http://just-the-time.appspot.com/')
datetime = time_url.read().decode("utf-8", errors="ignore").split(' ')[:-1]
date = datetime[0]
time = datetime[1]

print("Date: "+str(date))
print("Year: "+str(date.split('-')[0]))
print("Month: "+str(date.split('-')[1]))
print("Day: "+str(date.split('-')[2])+'\n')

print("Time: "+str(time))
print("Hour: "+str(time.split(':')[0]))
print("Minute: "+str(time.split(':')[1]))
print("Second: "+str(time.split(':')[2]))

Output will be like

Date: 2020-04-18
Year: 2020
Month: 04
Day: 18

Time: 14:17:10
Hour: 14
Minute: 17
Second: 10

Method3: Getting Current Date and Time from Local Time of the Machine

Python's time module provides a function for getting local time from the number of seconds elapsed since the epoch called localtime(). ctime() function takes seconds passed since epoch as an argument and returns a string representing local time.

Code

from time import time, ctime
datetime = ctime(time()).split(' ')

print("Date: "+str(datetime[4])+"-"+str(datetime[1])+"-"+str(datetime[2]))
print("Year: "+str(datetime[4]))
print("Month: "+str(datetime[1]))
print("Day: "+str(datetime[2]))
print("Week Day: "+str(datetime[0])+'\n')

print("Time: "+str(datetime[3]))
print("Hour: "+str(datetime[3]).split(':')[0])
print("Minute: "+str(datetime[3]).split(':')[1])
print("Second: "+str(datetime[3]).split(':')[2])

Output will be like

Date: 2020-Apr-18
Year: 2020
Month: Apr
Day: 18
Week Day: Sat

Time: 19:30:20
Hour: 19
Minute: 30
Second: 20

Upvotes: 13

Sai Kiran Sangam
Sai Kiran Sangam

Reputation: 368

You can do so using ctime():

from time import time, ctime
t = time()
ctime(t)

output:

Sat Sep 14 21:27:08 2019

These outputs are different because the timestamp returned by ctime() depends on your geographical location.

Upvotes: 13

champion-runner
champion-runner

Reputation: 1647

Current time of a timezone

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"))

tz_India = pytz.timezone('Asia/India')
datetime_India = datetime.now(tz_India)
print("India time:", datetime_India.strftime("%H:%M:%S"))

#list timezones
pytz.all_timezones

Upvotes: 19

Ben
Ben

Reputation: 4331

This question doesn't need a new answer just for the sake of it ... a shiny new-ish toy/module, however, is enough justification. That being the Pendulum library, which appears to do the sort of things which arrow attempted, except without the inherent flaws and bugs which beset arrow.

For instance, the answer to the original question:

>>> import pendulum
>>> print(pendulum.now())
2018-08-14T05:29:28.315802+10:00
>>> print(pendulum.now('utc'))
2018-08-13T19:29:35.051023+00:00

There's a lot of standards which need addressing, including multiple RFCs and ISOs, to worry about. Ever get them mixed up; not to worry, take a little look into dir(pendulum.constants) There's a bit more than RFC and ISO formats there, though.

When we say local, though what do we mean? Well I mean:

>>> print(pendulum.now().timezone_name)
Australia/Melbourne
>>>

Presumably most of the rest of you mean somewhere else.

And on it goes. Long story short: Pendulum attempts to do for date and time what requests did for HTTP. It's worth consideration, particularly for both its ease of use and extensive documentation.

Upvotes: 27

Jobin James
Jobin James

Reputation: 1030

import datetime

todays_date = datetime.date.today()
print(todays_date)
>>> 2019-10-12

# adding strftime will remove the seconds
current_time = datetime.datetime.now().strftime('%H:%M')
print(current_time)
>>> 23:38

Upvotes: 14

Sachin
Sachin

Reputation: 1704

This is so simple. Try:

import datetime
date_time = str(datetime.datetime.now())
date = date_time.split()[0]
time = date_time.split()[1]

Upvotes: 8

Related Questions