Python get current time in timezone

How to Get Current Date and Time in Python

You’ll learn how to get the current date and time in Python using the datetime and time module.

By the end of this article, you’ll learn

  • How to get current date and time in various formats
  • Get current time in seconds and miliseconds
  • Get current local time, UTC time, GMT time, ISO time.
  • How to get current time in the specific timezone

Table of contents

Steps to Get Curent Date and Time in Python

There are many ways to get the current date and time in Python using the built-in and third-party modules. The below steps show how to get the current date and time using the datetime and time module.

  1. Import datetime module Python’s datetime module provides functions that handle many complex functionalities involving the date and time. Import the datetime class using a from datetime import datetime statement.
  2. Use the now() function of a datetime class The datetime.now() returns the current local date and time. By default, it represents datetime in YYYY-mm-dd hh:mm:ss.microseconds format. Note: The date and time values are stored as datetime objects, The datetime object represents both date and time
  3. Use the today() function of a Date class Use this step if you want only the current date and not the time. The today() method of a date class returns the current local date
  4. Use time module Use the time.time() function to get the current time in seconds since the epoch as a floating-point number
Читайте также:  Python process list linux

Example: Get Current DateTime in Python

from datetime import datetime now = datetime.now() print('Current DateTime:', now) print('Type:', type(now))

Current DateTime: 2021-07-16 19:17:20.536991 Type:

As you can see in the output we got the current date and time in the following format.

Refer to Python DateTime Format Using Strftime() If you want to get the current date in various formats.

Extract Current Date and Time Separately from a Datetime Object

Note: in Python, The date and datetime are objects. So when we are manipulating date and time, that means we are actually dealing with objects.

For example, you can extract the current date and time separately from a datetime object

  • Use the date() function to get the date in yyyy-mm-dd format
  • Use the time() function to get the time in the hours:minutes:seconds.microseconds format.
# import only datetime class from datetime import datetime # current datetime now = datetime.now() current_date = now.date() print('Date:', current_date) print(type(current_date)) current_time = now.time() print('Time', current_time) print(type(current_time))

Date: 2021-07-16 Time 08:25:05.282627

Break DateTime to Get Current Year, Month, Day, Hour, Minute, Seconds

The datetime module provides several attributes to access the induvial component such as a year, month, day, hour, minute, seconds.

In this example, we’ll break the current datetime and assign them into variables like the year, month, day, hour, minute, seconds, and microseconds.

from datetime import datetime # Get current date and time now = datetime.now() # extract attributes print("Year:", now.year) print("Month:", now.month) print("Day =", now.day) print("Hour:", now.hour) print("Minute:", now.minute) print("Second:", now.second) print("Microsecond:", now.microsecond)
Year: 2021 Month: 7 Day = 16 Hour: 8 Minute: 28 Second: 0 Microsecond: 619640

Note: You can also use the datetime.timetuple() to break the datetime an get the induvial attribute for it.

Get Current Date using the Date class

Python Datetime module provides the Date class to represent and manipulate the dates. The Date class considers the Gregorian calendar.

  • Import the date class from the datetime module
  • Use the date.today() method to get the current date.
from datetime import date today = date.today() print('Current Date:', today) # Output 2021-07-16

Note: The datetime.today() return the current date and time. This method is functionally equivalent to now() , but without timezone information.

Get Current Time in Python

There are many ways to get the current time in Python using the built-in and third-party modules. Python time module provides various functions to get the current time and perform time-related activities. We will see each one by one

Current Time in Seconds Using time.time()

Use the time.time() function to get the current time in seconds since the epoch as a floating-point number.

This method returns the current timestamp in a floating-point number that represents the number of seconds since Jan 1, 1970, 00:00:00.

It returns the current time in seconds.microseconds format.

import time # get current time in seconds t = time.time() print('Time:', t) # Output 1626488018.0199707

You can use this timestamp to convert it into a datetime object also.

Current Time in MiliSeconds Using time.time()

Current Time Using time.ctime()

Use the time.ctime() function to display the current time in a human-readable format. This function represents the current time in the operating system preferred way. The output may vary as per the operating system.

import time # get current time print('Current Time:', time.ctime(time.time())) # Output Sat Jul 17 07:07:09 2021

Current Time Using time.localtime()

Use the time.localtime() function to return the current time expressed in seconds since the epoch to a local time in the a struct_time format.

You can access year, month, day, hour, minute, seconds, and microseconds from a struct_time .

import time # get current local time t = time.localtime(time.time()) print('Current Time:', t) print('Year:', t.tm_year) print('Month:', t.tm_mday) print('Day:', t.tm_mday) print('Minutes:', t.tm_min) print('Hours:', t.tm_hour) print('Seconds:', t.tm_sec)
Current Time: time.struct_time(tm_year=2021, tm_mon=7, tm_mday=17, tm_hour=7, tm_min=13, tm_sec=27, tm_wday=5, tm_yday=198, tm_isdst=0) Year: 2021 Month: 17 Day: 17 Minutes: 13 Hours: 7 Seconds: 27

Get Current Time Using Datetime Module

The datetime.now() method of a datetime class returns the current time in a human-readable format. It internally uses the time.localtime() without the timezone info (if not given).

Also, you can access the individual attribute such as hour, minutes, seconds, and microseconds

from datetime import datetime now = datetime.now() print('Current DateTime:', now) print('Current Time:', now.time())
Current DateTime: 2021-07-17 07:23:29.454555 Current Time: 07:23:29.454555

Get Current Time in Milliseconds

There is no specific attribute or method in Python to get the current time in milliseconds. However, as milliseconds are three decimal places away from seconds, we can convert seconds to milliseconds by multiplying seconds by 1000.

  • Use the time.time() to get the current time in seconds since the epoch as a floating point number
  • Multiply time by 1000 to get current time in milliseconds
import time t = time.time() ml = int(t * 1000) print('Current time in milliseconds:', ml) # Output 1626498089547

Get Current UTC Time

UTC – Coordinated Universal Time is the common time standard across the world. So, in Python, to work with the timezone without any issues, it is recommended to use the UTC as your base timezone.

  • Use the datetime.now() method to get the current time
  • Use the timezone class with UTC instance with a now() method to to get the current UTC time in Python
from datetime import datetime, timezone now = datetime.now(timezone.utc) print('Current UTC Time:', now)
Current UTC Time: 2021-07-17 01:59:25.017849+00:00

Get Current Time in a Specific Timezone

Use the third-party pytz module to get the current time of any timezone.

  • Install pytz module using the pip install pytz
  • Use the pytz.timezone(‘region_name’) function to create the timezone object
  • Use datetime.now(timezone_obj) function to get the current datetime with timezone
from datetime import datetime import pytz dt_us_central = datetime.now(pytz.timezone('US/Central')) print("US Central Current DateTime:", dt_us_central.strftime("%Y:%m:%d %H:%M:%S %Z %z")) # extract components print('TimeZone Name:', dt_us_central.tzname()) print('UTC offset:', dt_us_central.utcoffset())
US Central Current DateTime: 2021:07:16 21:06:18 CDT -0500 TimeZone Name: CDT UTC offset: -1 day, 19:00:00

Get Current GMT Time

Greenwich Mean Time or GMT is clock time at the Royal Observatory in Greenwich, London. It is not affected by Summer Time (Daylight Saving Time) clock changes.

GMT

  • Use the time.gmtime() method to get the current GMT time in Python
  • Pass the time in seconds to this method to get the GMT representation of a time
import time # current GMT Time gmt = time.gmtime(time.time()) print('GMT Time:', gmt) # Hours:minutes:Seconds print(gmt.tm_hour, ':', gmt.tm_min, ':', gmt.tm_sec) 
GMT Time: time.struct_time(tm_year=2021, tm_mon=7, tm_mday=17, tm_hour=6, tm_min=51, tm_sec=57, tm_wday=5, tm_yday=198, tm_isdst=0) 6:51:57

Get Current Time in ISO Format

Use the datetime.isoformat() method to get the current date and time in ISO format.

Use isoformat() method on a datetime.now() instance to get the current date and time in the following ISO 8601 format:

from datetime import datetime dt_iso = datetime.now().isoformat() print('Current DateTime in ISO:', dt_iso)
Current DateTime in ISO: 2021-07-17T10:42:44.106976

Conclusion

In this article, we learned to use the following Python functions to get the current date and time.

Function Description
datetime.now() Get the current local datetime, with no timezone information
date.today() Get the current date
time.time() Get the current time in seconds. It returns the number of seconds since Jan 1, 1970, 00:00:00.
time.ctime() Get the current time in a human-readable format
time.localtime() Get the current time expressed in seconds since the epoch to a local time in the a struct_time format
int(time.time() *1000) Get the current time in milliseconds
datetime.now(timezone.utc) Get the current UTC time
time.gmtime(time.time()) Get the current GMT time
datetime.now(pytz.timezone(‘tz_name’)) Get the current time in a specific timezone
datetime.now().isoformat() Get the current datetime in ISO format

Functions to get current date and time in Python

Did you find this page helpful? Let others know about it. Sharing helps me continue to create free Python resources.

About Vishal

I’m Vishal Hule, Founder of PYnative.com. I am a Python developer, and I love to write articles to help students, developers, and learners. Follow me on Twitter

Python Exercises and Quizzes

Free coding exercises and quizzes cover Python basics, data structure, data analytics, and more.

  • 15+ Topic-specific Exercises and Quizzes
  • Each Exercise contains 10 questions
  • Each Quiz contains 12-15 MCQ

Comments

Hi Vishal:
Excellent! Please check in the section Current Time Using time.localtime() , in the code you made a slight mistake

print('Year:', t.tm_year) print('Month:', t.tm_mday) #HERE => print('Month:', t.tm_mon) instead print('Day:', t.tm_mday)

Leave a Reply Cancel reply

All Python Topics

About PYnative

PYnative.com is for Python lovers. Here, You can get Tutorials, Exercises, and Quizzes to practice and improve your Python skills.

Explore Python

Follow Us

To get New Python Tutorials, Exercises, and Quizzes

We use cookies to improve your experience. While using PYnative, you agree to have read and accepted our Terms Of Use, Cookie Policy, and Privacy Policy.

Copyright © 2018–2023 pynative.com

Источник

Оцените статью