Formatting Date and Time:
the datetime module helps us in formatting date and time which is based on the locale that you have set. The effortless way is to depend on the function strftime() . It converts an object to a string according to a given format.which can either be a date, time, or datetime object.Now, , let us have a look at list of common format codes:
1)%A %u2013 weekday as locale%u2019s full name,
2)%b %u2013 month as locale%u2019s abbreviated name,
3)%m %u2013 month as a zero-padded decimal number,
4)%Y %u2013 year with century as a decimal number,
5)%H %u2013 hour (24-hour clock) as a zero-padded decimal number,
6)%I %u2013 hour (12-hour clock) as a zero-padded decimal number (capital %u201Ci%u201D),
7)%p %u2013 locale%u2019s equivalent of either AM or PM,
8)%M %u2013 minute as a zero-padded decimal number,
9)%S %u2013 second as a zero-padded decimal number,
10)%Z %u2013 time zone name (empty string if the object is naive).
we will now define the format in a string which we will use it as the input parameter when calling the strftime() function. Here is the following example which displays the current date and time.
now = datetime.datetime.now()
format = "%A, %d %b %Y %H:%M:%S %Z"
now.strftime(format)
# Thursday, 10 June 2021 16:11:31
If a value is stored as a timestamp in your database, you can easily convert it to a datetime object:
submission_date = datetime.datetime.fromtimestamp(1595485143)
format = "Submit before %A, %#I%p %d/%m/%Y"
submission_date.strftime(format)
# Submit before Thursday, 4PM 12/07/2020
%I here represents a 12-hour clock like a zero-padded decimal number. We can remove the leading zero by adding a hyphen or pound sign based on the operating system of your machine. For example,
1)Linux, OS X: %-I
2)Windows, Cygwin: %#I
You can highlight the timezone as long as the datetime object contains the optimal timezone information. We call this an aware datetime object. In contrast, a naive datetime object does not contain enough information to unambiguously locate itself in relation to other datetime objects. You can easily identify if a datetime object is aware or naive by printing it out.
We can easily construct and define a timezone in a datetime object by using datetime.timezone. have a look at the following example of creating instances of current datetime based on different timezones.
format = "Timezone: %H:%M:%S %Z"
# is a naive datetime object
now = datetime.datetime.now()
now.strftime(format)
# Timezone 15:24:29
now = datetime.datetime.now(tz=datetime.timezone.utc)
now.strftime(format)
# Timezone 07:24:29 UTC
# using UTC as timezone
now = datetime.datetime.now(tz=datetime.timezone(datetime.timedelta(hours=6)))
now.strftime(format)
# Timezone 13:24:29 UTC+06:0
Here %Z will return an empty string which is called by a naive datetime object
Comments