Working out Python Date and Time, with Examples — SitePoint

Working out Python Date and Time, with Examples — SitePoint

[ad_1]

On this article, we’ll discover easy methods to use date and time in Python. We’ll see real-life examples of operating with date and time the usage of the Python datetime and time modules.

Running with instances and dates is inevitable when development real-life initiatives, and there are lots of use circumstances for them. Fortunately, Python has a few modules that make it simple to paintings with dates and instances throughout other timezones.

The code for this instructional can also be discovered on GitHub.

Contents:

  1. The time Module
  2. The datetime Module
  3. Getting the Present Date and Time in Python
  4. Getting the Present Date in Python
  5. The datetime Module Categories
  6. The date Magnificence
  7. The time Magnificence
  8. The datetime Magnificence
  9. The timedelta Magnificence
  10. Python datetime Formatting
  11. Running with timedelta

The time Module

The Python time module is for appearing time-related operations. We’ll now spotlight one of the vital maximum frequently used purposes within the time module, with examples.

The time() serve as

The time() serve as returns the present time in seconds because the starting of a suite epoch as a floating level quantity. The epoch that’s used begins in January 1, 1970, 00:00:00 (UTC):

import time as time_module

time_in_seconds = time_module.time()
print("Time in sceconds from epoch", time_in_seconds)

Right here’s the output of the code above:

Time in sceconds from epoch 1680712853.0801558

The gmtime() serve as

The gmtime() serve as returns a struct_time in UTC from time expressed in seconds because the starting of the epoch. A struct_time is one of those time price series with a named tuple interface returned by means of gmtime(), localtime(), and strptime():

import time as time_module

utc_time_in_seconds = time_module.gmtime()
print("Time struct in UTC", utc_time_in_seconds)

Right here’s the output of the code above:

Time struct in UTC: time.struct_time(tm_year=2023, tm_mon=3, tm_mday=16, tm_hour=14, tm_min=47, tm_sec=28, tm_wday=3, tm_yday=75, tm_isdst=0)

The localtime() serve as

The localtime() serve as returns a struct_time in native time from time expressed in seconds because the starting of the epoch:

import time as time_module

local_time = time_module.localtime()
print("Time struct in native time:", local_time)

Right here’s the output of the code above:

Time struct in native time: time.struct_time(tm_year=2023, tm_mon=4, tm_mday=20, tm_hour=15, tm_min=46, tm_sec=15, tm_wday=3, tm_yday=75, tm_isdst=0)

The ctime() serve as

The ctime() manner converts time in seconds from the start of the epoch to a string layout. If no arguments are handed to the serve as, it returns a time string for the present time in seconds:

import time as time_module

time_in_secs = 1678671984.939945  

time_string = time_module.ctime(time_in_secs)
print("Time string: ",time_string)

Right here’s the output of the code above:

Time string: Thu Apr 20 01:46:24 2023

The strftime() serve as

The strftime() manner converts a struct_time to a time string as laid out in a given layout argument:

import time as time_module

time_tuple = time_module.gmtime()
time_format = "%y/%m/%d %I:%M:%S %p"

time_in_string = time_module.strftime(time_format, time_tuple)

print("Time expressed as formatted string:", time_in_string)

Right here’s the output of the code above:

Time expressed as formatted string: 23/04/20 04:40:04 PM

The sleep() serve as

The sleep() serve as delays the execution of a thread for a specified collection of seconds:

import time as time_module 

for i in vary(5):
    local_time = time_module.localtime()
    seconds = local_time.tm_sec
    print(seconds)
    time_module.sleep(2)

Right here’s the output of the code above:

Within the code above, the quantity 2 is handed in as an issue of the sleep() serve as, which reasons the loop to lengthen two seconds earlier than execution. The numbers which can be output validate our code.

The datetime Module

The datetime module provides categories for manipulating dates and instances.

Those categories are very important for simple manipulation, extraction, and output formatting of time durations, instances and dates. Ordinarily, date and time aren’t regarded as information varieties in Python, however they’re date and time items of the datetime module categories. Datetime categories even have other strategies to be had for dealing with date and time items.

Getting the Present Date and Time in Python

To get the present date and time, import the datetime elegance from the datetime module. The datetime elegance has one way, now(), which returns the present date and time:

from  datetime  import  datetime

current_date_time = datetime.now()
print(current_date_time)

Right here’s the output of the code above:

2023-04-20 13:47:02.362424

Getting the Present Date in Python

To get the present date, import the date elegance from the datetime module. The date elegance has one way, as of late(), which returns the present date:

from datetime import date

current_date = date.as of late()
print(current_date)

Right here’s the output of the code above:

The datetime Module Categories

The datetime module recently has six categories, each and every with other strategies for manipulating date and time items. The categories are indexed as follows:

  • date
  • time
  • datetime
  • timedelta
  • tzinfo
  • timezone

The date Magnificence

A date object represents a date (yr, month and day) in an idealized calendar — the present Gregorian calendar indefinitely prolonged in each instructions.

A date object can also be instantiated as follows:

datetime.date(yr, month, day)

The date object constructor takes 3 integer arguments and must be inside the specified vary:

  • MINYEAR <= yr <= MAXYEAR
  • 1 <= month <= 12
  • 1 <= day <= collection of days within the given month and yr

Within the code above, MINYEAR is 1 and MAXYEAR is 9999. The values constitute the smallest and largest yr quantity allowed in a date or datetime object.

When the arguments are out of vary, it throws a ValueError, and non-integer arguments throw a TypeError.

Instance: Create a date object

To create a date object, import the date elegance from the datetime module, and cross arguments for yr, month and day into the date constructor. The arguments will have to be integers and inside the specified vary:

from datetime import date

mydate = date(2023, 4, 20)
print('The date is: ', mydate)

Right here’s the output of the code above:

Instance: Get the present date

To get the present native date, use the date elegance as of late() and ctime() strategies:

from datetime import date

current_date = date.as of late()
print(current_date.ctime())

The as of late() manner will go back an area date, whilst the ctime() manner renders the date as a string.
Right here’s the output of the code above:

Instance: Create the date from ISO layout

A date object can also be comprised of a date string in ISO 8601 layout. Use the fromisoformat() manner of the date elegance to try this:

from datetime import date

iso_date = date.fromisoformat('2023-04-20')
print("Date from ISO layout: ", iso_date)

Word: ISO 8601 is a standardized layout for presenting dates and time with out growing confusion throughout other areas or timezones. ISO 8601 takes the layout YYYY-MM-DD.

Right here’s the output of the code above:

Date from ISO layout:  2023-04-20

Instance: Create date object from string

To create a date object, cross a date string and corresponding layout to the strptime() manner. Extract the date by means of the usage of the date() manner of the returned datetime object:

from datetime import datetime

datetime_object = datetime.strptime("20/04/23", "%d/%m/%y")
date_object = datetime_object.date()

print("Date from string:", date_object)

Right here’s the output of the code above:

Date from string: 2023-04-20

Instance: Get the yr, month, day from the date object

To extract the yr, month and day from a date object, use the .yr, .month, and .day attributes of the date elegance:

from datetime import date

current_date = date.as of late()

yr = current_date.yr
print("The yr is: ", yr)

month = current_date.month
print("The month is: ", month)

day = current_date.day
print("The day is: ", day)

Right here’s the output of the code above:

The yr is: 2023
The month is: 4
The day is: 20

The time Magnificence

A time object represents a (native) time of day, unbiased of any explicit day, and topic to adjustment by means of a tzinfo object.

A date object can also be instantiated as follows:

datetime.time(hour=0, minute=0, 2d=0, microsecond=0, tzinfo=None)

The time object can also be instantiated with none arguments. All arguments are non-compulsory with a default price of 0, except for tzinfo, which is None. All arguments will have to be integers inside a specified vary, whilst the tzinfo argument must be an example of the tzinfo subclass:

  • 0 <= hour < 24,
  • 0 <= minute < 60,
  • 0 <= 2d < 60,
  • 0 <= microsecond < 1000000.

When arguments which can be out of vary are handed to the constructor, it raises a ValueError.

Instance: Create a time object

To create a time object, import the time elegance from the datetime module. Move arguments for hours, mins, seconds, microseconds and tzinfo. Needless to say all arguments are non-compulsory, so when no argument is handed to the constructor, the time object returns 00:00:00:

from datetime import time

my_time = time(20, 30, 12)
print("My time is: ", my_time)

Right here’s the output of the code above:

Instance: Create time from ISO layout

A time object can also be comprised of a time string in ISO 8601 layout. Use the fromisoformat() manner of the time elegance to try this:

from datetime import time

iso_time = time.fromisoformat('12:45:12')
print('The time says: ', iso_time)

Right here’s the output of the code above:

Instance: Create time object from string

To create a time object, cross a date string and corresponding layout to the strptime() manner. Extract the time by means of the usage of the time() manner of the returned datetime object:

from datetime import datetime

datetime_object = datetime.strptime("20 Apr, 2023 13:50:30", "%d %b, %Y %H:%M:%S")
time_object = datetime_object.time()

print("Time from string:", time_object)

Right here’s the output of the code above:

Time from string: 13:50:30

Instance: Get hours, mins, seconds and microseconds from the time object

To extract values for hours, mins, seconds and microseconds, use the hour, minute, 2d, and microsecond attributes of the time object:

from datetime import time

new_time = time(7, 20, 50, 569230)

hour = new_time.hour
print('Hours: ',hour)

minute = new_time.minute
print('Mins: ', minute)

2d = new_time.2d
print('Seconds: ', 2d)

microsecond = new_time.microsecond
print('Microseconds: ', microsecond)

Right here’s the output of the code above:

Hours: 7
Mins: 20
Seconds: 50
Microseconds: 569230

The datetime Magnificence

A datetime object is a unmarried object containing all of the knowledge from a date object and a time object.

A datetime object can also be instantiated as follows:

datetime.datetime(yr, month, day, hour, minute=0, 2d=0, microsecond=0, tzinfo=None)

The datetime constructor calls for the yr, month and day arguments. The tzinfo default is None or an example of the tzinfo subclass. The time arguments are non-compulsory, however the arguments will have to be integers and inside vary:

  • MINYEAR <= yr <= MAXYEAR,
  • 1 <= month <= 12,
  • 1 <= day <= collection of days within the given month and yr,
  • 0 <= hour < 24,
  • 0 <= minute < 60,
  • 0 <= 2d < 60,
  • 0 <= microsecond < 1000000.

A ValueError is raised if arguments are out of vary.

Instance: Create a datetime object

To create a datetime object, import the datetime elegance from the datetime module and cross the next arguments:

from datetime import datetime

dt = datetime(2023, 4, 20, 10, 38, 10, 345389)

Right here’s the output of the code above:

The date time is: 2023-04-20 10:38:10.345389

Instance: Get the present native date and time

To get the present native date and time, use the now() manner of the datetime elegance:

from datetime import datetime

print('Present find date time is: ', datetime.now())

Right here’s the output of the code above:

Present find date time is: 2023-04-20 10:50:08.944232

Instance: Create date time from ISO layout

To create a datetime object from a date time string in ISO 8601 layout, use the fromisoformat() manner of the datetime elegance:

from datetime import datetime

iso_dt = datetime.fromisoformat('2023-04-20 11:25:30.983023')
print('Date time from ISO is: ', iso_dt)

Word: if the date string argument handed into the fromisoformat() manner isn’t a sound ISO layout string, a ValueError exception is raised. The date output here’s rather very similar to the end result download from datetime.now().

Right here’s the output of the code above:

Date time from ISO is: 2023-04-20 11:25:30.983023

Instance: Get date and time attributes from the datetime object

A datetime object gives the next attributes: yr, month, day, hour, minute, 2d, microsecond, tzinfo and fold. The attributes can also be accessed as follows:

from datetime import datetime

new_dt = datetime.now()

yr = new_dt.yr
print('Yr: ', yr)

month = new_dt.month
print('Month: ', month)

day = new_dt.day
print('Day: ', day)

hour = new_dt.hour
print('Hours: ', hour)

minute = new_dt.minute
print('Mins: ', minute)

2d = new_dt.2d
print('Seconds: ', 2d)

microsecond = new_dt.microsecond
print('Microseconds: ', microsecond)

tz_info = new_dt.tzinfo
print('Timezone data: ', tz_info)

fold = new_dt.fold
print('Fold: ', fold)

Right here’s the output of the code above:

Yr: 2023
Month: 4
Day: 20
Hours: 12
Mins: 42
Seconds: 15
Microseconds: 794955
Timezone data: None
Fold: O

Word: the default characteristic price for tzinfo is None, as a result of there’s no object argument handed, and fold will go back 0 by means of default. For extra at the fold characteristic (which used to be presented in Python model 3.6), see the medical doctors.

The timedelta Magnificence

A timedelta object represents a length, the adaptation between two dates or instances.

A timedelta object can also be instantiated as follows:

datetime.timedelta(days=0, seconds=0, microseconds=0, milliseconds=0, mins=0, hours=0, weeks=0)

All arguments are non-compulsory, with a default price of 0. Integers or floats, sure or unfavorable numbers are legitimate arguments for the constructor.

Arguments are transformed as follows:

  • A millisecond is transformed to 1000 microseconds.
  • A minute is transformed to 60 seconds.
  • An hour is transformed to 3600 seconds.
  • Per week is transformed to 7 days.

All arguments must fall inside the following vary as specified within the medical doctors:

  • 0 <= microseconds < 1000000
  • 0 <= seconds < 3600*24 (the collection of seconds in in the future)
  • -999999999 <= days <= 999999999

An OverFlowError is raised if arguments are outdoor the normalized days vary.

Instance: Create a timedelta object

To create a timedelta object, import the timedelta elegance from the datetime module. Move the best arguments to the constructor serve as:

from datetime import timedelta

td = timedelta(10, 30, 4300, 3000, 12, 5, 3)
print('Time Delta: ', td)

Right here’s the output of the code above:

Time Delta: 31 days, 5:12:33.004300

Python datetime Formatting

Date and time codecs fluctuate from area to area and nation to nation. It’s on account of those variations in date and time codecs that the ISO 8601 layout used to be presented, so that you could standardize date and time.
Alternatively, there is also a want to layout date and time in a specific manner in accordance with a rustic or area.

Formatting datetime with the strftime() manner

Datetime formatting can also be carried out with the strftime() manner. The strftime() manner is an example manner of time, date and datetime categories, which means that we need to create a date, time or datetime object to use the process. The process takes a given layout code as an issue, and returns a string representing time, date or datetime from within the desired layout.

The process signature looks as if this:

Generally a string layout code is handed as an issue to strftime() way to layout date. One of the vital layout codes are as follows:

  • %a: weekday abbreviated title — akin to Solar, Mon, and so on.
  • %b: month as abbreviated title — akin to Jan, Feb, and so on.
  • %y: yr with out century as a zero-padded decimal quantity — akin to 00, 01, 02, and so on.

A extra detailed desk with layout code can also be discovered within the Python medical doctors.

Instance: Structure date and time in a datetime object

Identical to within the earlier examples, we will cross an issue of the layout string of the specified date and time output to the strftime() manner:

from datetime import datetime

date_time = datetime.now()

formatted_date_time = date_time.strftime("%d %B %Y, %H:%M:%S")
print("Formatted date and time:", formatted_date_time)

formatted_date_time_2 = date_time.strftime("%A, %d %B %Y, %I:%M %p")
print("Formatted date and time in 12-hour clock:", formatted_date_time_2)

Right here’s the output of the code above:

Formatted date and time: 20 April 2023, 11:11:40
Formatted date and time in 12-hour clock: Thursday, 20 April 2023, 11:11 AM

Formatting datetime with the strptime() manner

Not like strftime(), the strptime() is a datetime elegance manner, which means that it may be used with out growing an object of the category. The process returns a datetime object from a given date string and layout.

The process signature looks as if this:

strptime(date_string, layout)

A string layout code is handed as an issue to strptime() way to layout date.

Instance: String to datetime object

To create a datetime object, we’ll cross two arguments to the strptime() manner, a date string and a corresponding layout. A ValueError is raised when the date string doesn’t fit the equipped layout:

from datetime import datetime

date_string = "April 20, 23 12:12:20"
dt_format = "%B %d, %y %H:%M:%S"

datetime_from_string = datetime.strptime(date_string, dt_format)
print("Datetime from string:", datetime_from_string)

Right here’s the output of the code above:

Datetime from string: 2023-04-20 12:12:20

Running with timedelta

The timedelta elegance in Python is used for calculating the adaptation between dates, calculating time variations between explicit dates, and likewise appearing different calculations the usage of explicit gadgets of time (akin to weeks or hours).

Instance: Calculate a long term date

from datetime import datetime, timedelta

date_now = datetime.now()
print("These days's date:", date_now)

future_date = date_now + timedelta(days=7)
print("Long term date is:", future_date)

Right here’s the output of the code above:

These days's date: 2023-04-20 15:50:43.415319
Long term date is: 2023-04-27 15:50:43.415319

From the instance above, we first get a present native date and time and a timedelta object of 7 days. As a result of timedelta helps operations like addition, we upload the datetime object and timedelta object to get a long term day in seven days. If our present date is 2023-04-20, in seven days the date shall be 2023-04-27.

Instance: Calculate the adaptation between two timedelta items

from datetime import timedelta

time_delta1 = timedelta(days=23, hours=0, mins=20)
time_delta2 = timedelta(days=15, seconds=2, microseconds=123, milliseconds=234566, mins=5, hours=2)

end result = time_delta1 - time_delta2

print("Distinction between two timedelta items:", end result)

Right here’s the output of the code above:

Distinction between two timedelta items: 7 days, 22:11:03.433877

Within the code snippet above, we’ve created two timedelta items, time_delta1 and time_delta2, and calculated the adaptation between them.

Instance: Calculate the sum of 2 timedelta items

from datetime import timedelta

time_delta1 = timedelta(days = 2, hours = 1, seconds = 33, weeks=2)
time_delta2 = timedelta(days = 4, hours = 11, mins = 4, seconds = 54)

end result = time_delta1 + time_delta2

print("Sum of 2 delta items:", end result)

Right here’s the output of the code above:

Sum of 2 delta items: 20 days, 12:05:27

As noticed above, the timedelta items beef up addition operation, and the result’s output to the console. Timedelta items beef up operations like subtraction, multiplication, and department.

Running with Timezones

Using timezones is important if we need to create mindful date and time items. An mindful time or date object contains knowledge at the timezone. It’s additionally essential for showing time or date items in the case of a specific area.

zoneinfo is a integrated Python module for operating with timezones.

Instance: Create a datetime object with timezone knowledge

from datetime import datetime
from zoneinfo import ZoneInfo

tz = ZoneInfo('Africa/Accra')
date_time_object = datetime.now(tz)

print("Timezone knowledge", date_time_object.tzinfo)
print("Timezone code", date_time_object.tzname())

Right here’s the output for the code above:

Timezone knowledge: Africa/Accra
Timezone code: GMT

First, we import the datetime elegance from the datetime module and ZoneInfo from the zoneinfo module. We create a ZoneInfo object after which a datetime object, however this time we cross the timezone object tz to the now() manner.

After we test the price of the tzinfo characteristic, it returns the title of the timezone Africa/Accra, no longer None.

Instance: Convert a datetime object from one timezone to any other

from datetime import datetime
from zoneinfo import ZoneInfo

accra_timezone = ZoneInfo('Africa/Accra')
accra_datetime = datetime.now(accra_timezone)
print("Present date time in Accra:", accra_datetime)


new_york_timezone = ZoneInfo('The usa/New_York')
new_york_datetime = accra_datetime.astimezone(new_york_timezone)
print("Present date time in New York:", new_york_datetime)

Right here’s the output of the code above:

Present date time in Accra 2023-04-20 10:42:02.476541+00:00
Present date time in New York 2023-04-20 06:42:02.476541-04:00

To transform between timezones, we use the astimezone() manner of the datetime object, passing in a brand new timezone object. The astimezone() returns a brand new datetime object with up to date timezone knowledge.

Conclusion

Keeping an eye on time is crucial facet of our day by day lives, and this additionally interprets into programming. After we construct real-world initiatives, there’s at all times the want to stay time logs for person actions like login and sign-out, amongst different use circumstances. It’s additionally essential to position a time stamp on content material generated on-line and to show time and date in step with a person’s area or timezone.

To raised set up instances and dates in our systems or packages, Python supplies the time and datetime modules. Those modules have purposes, categories and strategies for managing time-related duties. On this article, we’ve highlighted some frequently used purposes and strategies, offering examples of the way they are able to be used.

The code for this instructional can also be discovered on GitHub.



[ad_2]

0 0 votes
Article Rating
Subscribe
Notify of
guest
0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
Back To Top
0
Would love your thoughts, please comment.x
()
x