Python Time without seconds - python

So I need to display current time, I only print now.hour and now.minutes, however there is always 00 that's displayed for seconds that I would like to take away
this is my code
now = datetime.datetime.now()
print(datetime.time(now.hour, now.minute))
this is my out put
16:40:00

You can use strftime to format the time stored in now.
now
>2020-02-17 09:47:52.429173
print(datetime.strftime(now, '%H:%M'))
09:47
The string located in datetime.strftime(--, 'here') defines the formatting that will be returned. You can find more of strftime's formatting specifications here.

Related

Formatting the time slot of a Pylon's deform.widget.DateTimeInputWidget

Needs
I need to customize a deform.widget.DateTimeInputWidget, especially to get rid of the seconds in the input time slot so that the user doesn't need to specify them. By default seconds have to be filled but I'm only interested in hours (24h based) and minutes.
Default deform DateTimeInputWidget. How to get rid of those pesky seconds in the time slot?
What I found
I was really attracted by the option called time_options in the doc, but it only says:
time_options
A dictionary of time options passed to pickadate.
without any example of such dictionary. This is apparently needed to feed this JavaScript code: https://github.com/amsul/pickadate.js/blob/master/lib/picker.time.js but I don't really know where and how by looking at this code.
Even more confusing is the fact that the default value ( default_time_options) which is hard coded is not a dictionary: https://github.com/Pylons/deform/blob/f4da7dffb0b9235babe4e99596eefd1a6170c640/deform/widget.py#L696 is a tuple of tuples, which is then converted into a dict: https://github.com/Pylons/deform/blob/f4da7dffb0b9235babe4e99596eefd1a6170c640/deform/widget.py#L737-L741
And from the example, this (("format", "h:i A"), ("interval", 30)) is transformed into: {'format': 'h:i A', 'interval': 30}.
The thing I don't understand here is the format itself: 'h:i A'. It's quite obscure to me as it doesn't seem to rely on any of the standard format for formatting a time string in Python (https://strftime.org/).
Question
Hence my question: how could I force the time part of the deform.widget.DateTimeInputWidget to be like: %H:%M ?
With %H = hour (24-hour clock) as a zero-padded decimal number and %M = Minute as a zero-padded decimal number, as described in: to https://strftime.org/
Or some format which would lead to the same output, e.g. 00:01, 06:15, 10:10, 18:00 or 23:59.
I finally ended up at the right place:
https://amsul.ca/pickadate.js/time/#formats
where one can see in the time picker documentation how it is build in JavaScript:
$('.timepicker').pickatime({
// Escape any “rule” characters with an exclamation mark (!).
format: 'T!ime selected: h:i a',
formatLabel: '<b>h</b>:i <!i>a</!i>',
formatSubmit: 'HH:i',
hiddenPrefix: 'prefix__',
hiddenSuffix: '__suffix'
})
In addition with the quite "unusual" (I have never ever seen i for formatting minutes before, neither a or A for the day period...) formatting rules: https://amsul.ca/pickadate.js/time/#formatting-rules
Same goes for the date picker if by any chances you are also interested in formatting dates: https://amsul.ca/pickadate.js/date/#formatting-rules
Then from Python, you can set the time_options and/or the date_options in your deform.widget.DateTimeInputWidget as follow:
time_options = {
'format': 'HH:i',
'formatLabel': 'HH:i',
}
or any other of the format options as standard key:value pairs.
Same goes for the date_options, e.g.:
date_options = {
'format': 'dd-mm-yyyy',
}
Notice: in some situations, this may not be taken into account in a private browsing window (I don't know why, I simply noticed that).

Date iso format python

I have this date form in python that I am writing on an api: 2022-06-01T10:36:56.000Z How can I turn this into a second? Thanks for your comments
I would like to use the seconds I have to do addition division and then go back to day/date/hour format
I can't find any content on the internet
Python cannot handle all type of iso formatted date strings. So you can use isodate library or remove .000Z from the string parsing.
You can be more clear on seconds though, is it total seconds elapsed from 1970, Jan 1 or seconds part in the date ?
k = datetime.fromisoformat("2022-06-01T10:36:56.000Z".replace(".000Z", ""))
k.timestamp()

datetime string (from python) to matlab

I have a datatime string (which comes from django/python) which looks like so:
datatime_str='2020-08-18 16:48:13.722422+00:00'
I then do, in Matlab 2018a:
fmt_dt='yyyy-MM-dd HH:mm:ss.SSSSSS+HH:mm';
datetime(datatime_str,'TimeZone','local','Format',fmt_dt);
and I get:
2020-08-18 00:00:13.722422+00:00
I am not sure what it is that I am doing wrong, but the result is obviously wrong :(
Any help would be great
Yes the +00:00 should be formatted as timezone, not hours, minute. However, you can set the display format as you would like, and this could be different from the input. The default Matlab datetime display format discards the fractional seconds (and also the timezone I think). For example:
fmt_dt_input='yyyy-MM-dd HH:mm:ss.SSSSSSxxxxx';
fmt_dt_show='yyyy-MM-dd HH:mm:ss.SSSSSS xxxxx';
datatime_str='2020-08-18 16:48:13.722422+00:00';
t = datetime(datatime_str,'InputFormat',fmt_dt_input,'TimeZone','local','Format',fmt_dt_show)
Has as output: 2020-08-18 16:48:13.722422 +00:00
EDIT: btw this info on datetime can be found here
your input string contains a UTC offset at the end, +00:00 which you parse as hours and minutes - that is why they are set to 00:00 in the result. Use e.g.
datetime('2020-08-18 16:48:13.722422+00:00', 'InputFormat', 'yyyy-MM-dd HH:mm:ss.SSSSSSZ', 'TimeZone', 'UTC')
instead (change the TimeZone parameter to whatever you need).

Python get total seconds from datetime results in occasional mistakes

I'm trying to follow these answers and get the elapsed seconds since Jan 1st 1970 for each element in my array (my_times). I'm then using these values to find the time intervals between each consecutive time. Either approach I take seems to give the wrong answer for at least one pair of times.
Mark Byers answer
To get the seconds since Jan 1st 1970, he suggested to try:
time.mktime(my_time.timetuple())
However this does not seem to work for times "2017-11-05 01:46:00+00" and "2017-11-05 01:47:00+00".
When I run the below code, it says the values are separated by 3660.0 seconds instead of 60.0 seconds
from datetime import datetime
import time
my_time1 = datetime.strptime("2017-11-05 01:46:00+00", "%Y-%m-%d %H:%M:%S+%f")
my_time2 = datetime.strptime("2017-11-05 01:47:00+00", "%Y-%m-%d %H:%M:%S+%f")
time.mktime(my_time2.timetuple()) - time.mktime(my_time1.timetuple())
Andrzej Pronobis' answer
To get the seconds since Jan 1st 1970, he suggested to try:
my_time.timestamp()
This fixed the two earlier times however it no longer works for times "2017-11-05 01:59:00+00" and "2017-11-05 02:00:00+00". The same issue appears, I get 3660.0 seconds instead of 60.0 seconds
from datetime import datetime
my_time1 = datetime.strptime("2017-11-05 01:59:00+00", "%Y-%m-%d %H:%M:%S+%f")
my_time2 = datetime.strptime("2017-11-05 02:00:00+00", "%Y-%m-%d %H:%M:%S+%f")
my_time2.timestamp() - my_time1.timestamp()
I'd like to know if I'm doing anything wrong? Also is there a better way to find all consecutive time intervals when the datetime is given as a String?
Edit:
Thank you John, that fixed the problem. Oddly, changing the format from +%f to %z still ran into the same issue.
What did work was running sudo ln -sf /usr/share/zoneinfo/UTC /etc/localtime (changes my computer's time to UTC) and then evaluating all the times
This is a case of "garbage in, garbage out." Here:
datetime.strptime("2017-11-05 01:59:00+00", "%Y-%m-%d %H:%M:%S+%f")
You probably think that +00 on the end means "UTC time", but the %f format specifier means "fractional seconds."
In any case, you're apparently running on a system where the time zone is set to one with daylight saving time part of the year. 2 AM happens twice on the DST changeover date in November, so your code is working as written (it's ambiguous, basically).
Put another way: your issue is not that you're computing time deltas incorrectly. Your issue is that you are loading the times from strings incorrectly (or ambiguously).

How do I get the current time and date of the operating system

How do I get the current time and date of the operating system (the one in the clock). I tried to use datetime.now(). But it returns different value.
As suggested by mcalex I've rechecked the time and date setting and this has always been like this:
Use time.localtime().
From https://docs.python.org/2/library/time.html#time.localtime
Like gmtime() but converts to local time. If secs is not provided or
None, the current time as returned by time() is used. The dst flag is
set to 1 when DST applies to the given time.
You can use the Python time module for various time-related functions. It appears you are requesting the following format:
Day Month Hour:Min:Sec Year
If so, you can use the following:
>>> import time
>>> time.asctime(time.localtime())
'Mon Jun 30 22:19:34 2014'
To convert to a specific format, you can use the following function:
time.strftime(format[, t])
This converts a struct_time object tm representing a time as returned by gmtime() or localtime() to a string. See the following link for more info on the format codes:
https://docs.python.org/2/library/time.html#time.localtime
Source: Beazley, D. M., "Python Essential Reference", 4th. Ed.

Categories