Python Date and Time
Python has a built in datetime
module to work with dates and times.
1. Getting Current Date and Time:
Use datetime.now()
:
import datetime
current_datetime = datetime.datetime.now()
print(current_datetime) # Prints current date and time
# Output :2024-07-30 12:24:34.675567
#
2. Getting Current Date:
Get current date use datetime.date.today()
or datetime.now().date()
:
import datetime
current_date=datetime.date.today()
print(current_date) # prints current date
#output: 2024-07-30
today = datetime.datetime.now().date() # Get today's date
print(today) #output: 2024-07-30
3. Creating Date Objects:
Create via the datetime.date(year, month, day)
constructor, assuming valid numerical parameters within date-time context such that values before type conversions (via casting or implicitly due to context like int + float without warnings during operation rather than by keyword before such operation on mixed floating point types) occur assuming explicit handling only within current program where values also verifiable unlike testing non-localized cases after code modification since same implicit or unapparent implicit float calculations without also verifying float outputs given original types of numerical inputs from data, or after modification, might occur before assignment to next op result using either explicit typecasting to intended rather than assuming given output (if both cases not also validated after) with valid operations/casting where needed given output type like string assignment with integers
import datetime
my_date = datetime.date(2024, 7, 28) # Create a date object
print(my_date) # Output:2024-07-28
# my_date2 = datetime.date(2024,13,43) #invalid month and day value during tests will cause error `ValueError: month must be in 1..12` for specific argument types provided which must validate during test to keep type correctness/handling across cases unless types always given when declaring in that Python program
4. Creating Time Objects
Constructor-based with these ordered keyword parameters (`hour`, `minute`, `second`, `microsecond`, `tzinfo`), like previous construct without extra testing where timezone would make little sense or without microsecond unless that value validated after rather than assumed unless explicitly specified in some unit or format after/during conversion, assuming value in scope used correctly across calls even after typecast within non-explicit scopes where value changed implicitly. Example use of `tzinfo` using UTC (Coordinated Universal Time) which is in effect one kind of offset if validating/converting against machine/operating system defaults that may handle time in various alternative formats not related to Greenwich mean or UTC which might introduce timezone difference values after or during math calculations even within some explicit step such as summing with microseconds given integer arithmetic for datetime construct methods which would work unless different formatting required then such as via rounding fractional parts by another function and using similar function call to print in different output style with appropriate locale, date-time or format parameters since could handle in various different locale settings unlike cases with implicit number casting using Python built-in operations like in prior samples showing string/number handling issues after those converted implicitly or when validating against known input to output after type changes:
import datetime
time1 = datetime.time(11,34,56)
print (time1) #11:34:56 without need to check type conversions by using the datetime provided helper functions which in most code would generally simplify/be better approach instead if doing lots of similar output operations with same types rather than typecast repeatedly even for valid ops if checking manually after even when implicit would otherwise produce `float` results for mixed numerical rather than erroring as would happen in other steps without testing given context e.g. set using ints after explicit float value assigned which unlike List-index operation would raise TypeError when it's being set this way if incorrect cast or that value from preceding operation not verified (or assigned via int, explicitly before sum like in code previously) as this datetime-related function call implies instead
# with arguments for optional parameters: assumes time information or usage assumes these are used in intended format like hh:mm:ss during calculations which for cases in code using special cases where implicit or other functions are used for time calculations might not appear that way in results later like when doing nested string calculations to construct outputs given that the `print()` formatting differs unlike checking via typecasts where implicit ones happen before assignment at time. These do not imply or introduce typecasts before they're needed if not assigned by specific steps so tests and operations can show appropriate result whether for mixed numeric like float results from math, and even though such testing not implemented using separate Boolean tests/code here at call: this assumption valid for DateTime usage but not necessarily by how others are invoked if those values end up modifying type after such implicit changes like when str variable in set produces crash given `TypeError` in explicit conversion due to invalid `int`/float, as example shows
mytime = datetime.time(11,34,56,234566)
print(mytime) # 11:34:56.234566 output from Python code.
current_time = datetime.datetime.now().time()
print(current_time) # current time
5. The timedelta Object
Instance via datetime class creates difference instance for two or more `datetime` instances during calculations/comparison, like when dealing with data between records when each stored within some sequential index list with matching type-conversions, you ensure consistent logic or validate inputs match outputs by tests where some type may remain numeric float after conversion since that suffices to sum with an expected floating numeric rather than convert int which would result in float after op rather than be cast earlier without further validation before assignment unlike where similar dict element access checks after `.pop` steps in code previously do discard so we could assume such differences given valid start->end rather than empty if those given too or from data since `ValueError` exists like date out-of-range from prior date setup examples shown here also
import datetime
time_current = datetime.datetime.now()
print(time_current) #current date and time
time_past = datetime.datetime(2023, 7, 20,11,23,45) # datetime of the past
timediff= time_current- time_past
# returns the time difference which gives you a new "time delta" variable via such function operations as here which can modify a given initial date time even if immutable by increment rather than needing to clone assuming other variables using initial if both needed such as in some range which timedelta object could handle/count using iterator assuming correct type-related behavior unlike simple numeric calculation which implicitly can return float-style numeric but doesn't work the same if summing indices where no automatic or fractional conversion desired given start-end bounds for an expected/verified integer increment/loop
print (timediff)
# currentdatetime + datetime.timedelta() : # create datetime variables or related instances which remains one means to do math or calculate valid data within datetime rather than needing conversions where each time-related operation does retain types correctly in subsequent comparisons if those assumed here where `datetime.date` returns/is correct without need to convert into int or similar despite using for calculations using number as argument if other args all int before assignment even after such operations during validation which simplifies testing after/if output needs type conversions for another context
6. Formatting Dates and Times:
Using a method given string specifier creates various formats from instances. Directive sequence or format given by string which remains similar and follows standard or documented syntax across languages/Python where you've a strftime
function with similar argument patterns by order/naming which outputs given a variable, if suitable formatting or other `DateTime` string, assuming such `str` types generated here or via typecasts prior rather than raising `TypeError` or similar as result. Common format given showing each usage unlike before where might use index/set in same example while in many use cases those functions are usually not intended that way rather only give correct outputs based upon provided argument inputs where here the output depends mainly on DateTime input sequence data, e.g., for microseconds you have special code and without it only current system `Time` gives correct result and that changes each moment hence special function needed and it implicitly assumes microseconds even if those not validated using tests which check they exist/etc and doesn't test that unless converting or printing by another special DateTime type conversion in other steps even if output uses number or float given other function argument sequences earlier, such behaviour differing for this reason from similar code calling math functions like sum using numbers inside set-object example due to different DateTime usage here unlike explicit set math shown previously using elements or `del` keywords since they always act by unique key/type only as opposed to implicit type casting on ints done there too by set to avoid those TypeErrors
- `%Y` : Year with century (e.g. 2024)
- `%y` Year without century (e.g. 24)
- `%m`: Month as a zero-padded decimal number.
- `%B`: Full month name
- `%b` Abbreviated month name
- `%d`: Day of the month as a zero-padded decimal number
- `%A`: Weekday full name.
- `%a`: Weekday abbreviated name.
- `%w` Weekday as decimal number, where 0 = "Sunday"
- `%H`: Hour (24-hour clock) as a zero-padded decimal number.
- `%I`: Hour (12-hour clock) as a zero-padded decimal number.
- `%p` Locale’s equivalent of either AM or PM.
- `%M`: Minute as a zero-padded decimal number.
- `%S`: Second as a zero-padded decimal number.
- `%f`: Microsecond as a decimal number, zero-padded on the left
- `%z`: UTC offset in the form +HHMM or -HHMM (empty string if the object is naive).
- `%Z`: Time zone name (empty string if the object is naive)
- `%j`: Day of the year as a zero-padded decimal number.
- `%U`: Week number of the year (Sunday as the first day of the week) as a zero padded decimal number. All days in a new year preceding the first Sunday are considered to be in week 0.
- `%W`: Week number of the year (Monday as the first day of the week) as a zero-padded decimal number. All days in a new year preceding the first Monday are considered to be in week 0.
- `%c`: Locale’s appropriate date and time representation.
- `%x`: Locale’s appropriate date representation.
- `%X`: Locale’s appropriate time representation.
- `%%`: A literal '%' character.
import datetime
dt = datetime.datetime(2024,7,30,13,35,45) # datetime with values for simplicity/illustration rather than using some dynamically produced values. Also shows default assumed formatting or that each value needed if DateTime-related math functions or constructors/class used directly. E.g. using fewer values, like current Date rather than including h/m/s data as before implies different intended function since assumed microsecond etc are also known and given in other methods even implicitly (like utc or related examples when implicit casting or conversion within an assignment may give error when also validating outputs rather than relying upon the conversion alone if only for some inputs like strings without quotes implying such ints valid where such types alone don't apply within Python datetimes in all its formatting possibilities hence datetime using this specific ordering where values may be null)
date_format = dt.strftime("%Y-%m-%d")
print(date_format) # Output : 2024-07-30
datetime_format = dt.strftime("%Y-%m-%d %H:%M:%S")
print(datetime_format) # 2024-07-30 13:35:45
7. Working with Time Zones:
Python `datetime` naive: by default lacks timezone info, whereas "aware" datetimes do, which become necessary when verifying against clock that automatically calculates or makes certain conversions from device where operating system datetime calculations don't involve/use Python which could return valid type or raise ValueError
or other like if converting time from a string with and without microseconds despite both producing valid numeric or types but end up in conflict due to missing parameters when these values combined despite the DateTime construct functions not implying sequence which still matters unlike dict access that assumes keys can contain anything that evaluates like set items/is hashable for these uses with similar considerations to check if valid key present unlike Lists which throw other index error exception or like comparing by same pointer (c=a) or that variables a and c contain same values even when original contents of b also fully equivalent and correct at earlier instance prior copy by reference
Using the `pytz` third-party lib for handling timezones effectively since handles most timezone scenarios: `pip install pytz`. To show example timezone given code block with UTC since already has relevant definition/functions built-in that are then useful for datetime which would still apply, unless another tz included for non-utc examples
import datetime
import pytz # first pip install pytz
# UTC Time
utcmoment_naive = datetime.datetime.utcnow() #naive by default which may make later timezone conversions inaccurate without an explicit typecast even for simple usages like print outputs shown here despite other conversion methods when handling date/time within more specific context during arithmetic for increment given how delta is added rather than calculating duration where the final output must preserve similar microseconds in other calculations like sum but with floats given mixed `int+float` calculations which without checking outputs after implicit or non-local scope can fail similarly by producing exception assuming implicit conversion handled despite resulting fractional parts in math when `str()` could work even in implicit use inside similar sums to append str parts to numeric where such string style usage with math and datetime still valid without using more special case formatted output as given when calling method function. So this naïve example shows output from call assuming known output type despite the datetime formats differing slightly given different purposes and code required given intended use which unlike simple numeric float still might require typecasting with format-style calls in that example to give results which align better unlike these DateTime methods showing such output style after conversions where possible issues from string inputs and not just conversions might introduce type inconsistencies like checking float precision assuming that these issues checked given initial floating precision for datetime
print(utcmoment_naive)
#make datetime aware
aware_utcnow = utcmoment_naive.replace(tzinfo=pytz.utc)
print(aware_utcnow)