I am using following code to get current time in python.
import datetime
now = datetime.datetime.now()
message_sent_time = now.strftime("%I:%M %p")
It returns time as
06:58 PM
However, I would like to get output as
6:58 PM
i.e. single digit time when time is before 10. How can I achieve it?
You can get a single-digit hour using %-I:
>>> message_sent_time = now.strftime("%-I:%M %p")
>>> print(message_sent_time)
7:07 PM
Full strftime formatting reference: http://strftime.org/
Related
I'm trying to investigate the Python time striptime method to decompose a time represented as 11:49:57.74. The standard %H, %M, %S are able to decompose the hour , minute , second. However, since the data is a string ( which is taken in python pandas column as datatype object, the Milliseconds after the decimal second is left uninterpreted. Hence, I get an error. Could someone please advise how to parse the example so that the seconds and microseconds are correctly interpreted from the time string ?
I would then use them to find the time delta between two time stamps.
I don't know if I had correctly understood your question.
So, to convert that string time to datetime and calculate the timedelta between two times you need to do as follow:
timedelta = str() #declare an empty string where save the timedelta
my_string = '11:49:57.74' # first example time
another_example_time = '13:49:57.74' #second example time, invented by me for the example
first_time = datetime.strptime(my_string, "%H:%M:%S.%f") # extract the first time
second_time = datetime.strptime(another_example_time , "%H:%M:%S.%f") # extract the second time
#calculate the time delta
if(first_time > second_time):
timedelta = first_time - second_time
else:
timedelta = second_time - first_time
print "The timedelta between %s and %s is: %s" % (first_time, second_time, timedelta)
Here obviusly you don't have any date, so the datetime library as default use 1900-01-01 as you can see in the result of the print:
The timedelta between 1900-01-01 11:49:57.740000 and 1900-01-01 13:49:57.740000 is: 2:00:00
I hope this solution is what you need. Next time provide a little bit more information please, or share an example with the code that you have tried to write.
Is there a way to get the current date in ballerina?
As I was browsing through some code examples I came across the syntax to get the current time. Shown below is how to get the current date in Ballerina:
Note: first you have to import the time package given below for this to work.
import ballerina/time;
Then put the following lines of code:
time: Time currentTime = time:[currentTime][2]();
string customTimeString = currentTime.format("dd-MM-yyyy");
This will give the following output:
08-07-2018
This is work for ballerina 0.991 and 1.0 first you have to import the time package
Then it will give the current date if you want to get in a format it will included the code
import ballerina/time;
To get current time
time:Time time = time:currentTime();
string standardTimeString = time:toString(time);
io:println("Current system time in ISO format: ", standardTimeString);
To format the time
string|error customTimeString = time:format(time, "yyyy-MM-dd-E");
if (customTimeString is string) {
io:println("Current system time in custom format: ", customTimeString);
}
y -Years
M -months
d -date
E -day
h -hour
m -Minuit
s -seconds
For Swan Lake Update 3 they seem to have removed the time:currentTime() function.
It seems they have replaced it with time:utcNow().
According to the ballerina documentation,
"The time:Utc is the tuple representation of the UTC. The UTC represents the number of seconds from a specified epoch. Here, the epoch is the UNIX epoch of 1970-01-01T00:00:00Z."
So you can convert this above tuple representation to RFC 3339 timestamp by using,
time:Utc currTime = time:utcNow();
string date = time:utcToString(currTime);
io:println(date);
Then you will get a result like below,
2023-01-14T17:04:15.639510400Z
Using ballerina time library you can convert to other different representations as well.
I edited and saved a text file, "fullname" on my Windows 7 computer.
I ran the following two lines of code immediately after saving the edits to "fullname", and I expected both of the following lines of code to return almost the same number of seconds since the epoch:
print str(os.path.getmtime(fullname))
print str(time.mktime(t.timetuple()))
The second line of code was borrowed from How to convert a Python datetime object to seconds
The results were not even close:
"1494082110.0"
"1319180400.0"
I would like to know why the results were not close.
My ultimate goal is that I want to know how to generate a float date, matching a calendar date of my choosing,
for use in the context of:
win32file.SetFileTime(handle, CreatedTime , AccessTime , WrittenTime )
Any help in understanding these issues would be much appreciated.
You need to compare the current time with the time at which you saved the file. In this code I save a file, then I get the current time in t and display it, then I get the modification time for the file and display that. You may note that the two times differ by less than a half a second.
>>> import datetime
>>> import time
>>> import os
>>> fullname = 'temp.txt'
>>> open('temp.txt', 'w').write('something')
9
>>> t = datetime.datetime.now()
>>> time.mktime(t.timetuple())
1502039202.0
>>> os.path.getmtime(fullname)
1502039187.4629886
I notice too that,
>>> datetime.datetime.fromtimestamp(1319180400)
datetime.datetime(2011, 10, 21, 3, 0)
In other words, that second number in your question yields a date that came before you put your question.
I need to stop a process at 8:00 PM PDT everyday or as soon as possible after 8:00 PM. I see a lot about other uses of the time function but the examples all seem to be a difference in time, the timing of something, or always have the date included.
Could someone please provide an example along the lines of how I make something like this work...?
if currenttime >= 8:00 PM PDT:
time.sleep(99999999)
And also, what will I need to import, and how do I do the import?
the method I know is:
import datetime #this is the way to import a module named datetime...
import time #this module is used to sleep
a = str(datetime.datetime.now()) #a = '2016-03-27 00:20:28.107000' #for example
a = a.split(' ')[1] #get rid of the date and keep only the '00:20:28.107000' part
if a.startwith('20:00'): time.sleep(3600*12) #sleep for 12 hours (43200 seconds)
hope this helps you
edit: change timezone to pdt:
import datetime,pytz #for python_TimeZone
a = str(datetime.datetime.now(pytz.timezone('US/Pacific'))) #basically get the time in the specified zone
#from here continue as above...
taken from: http://www.saltycrane.com/blog/2009/05/converting-time-zones-datetime-objects-python/
good luck (next time try searching it in google...)
I actually ended up using a combination of hai tederry's answer and that found on http://www.saltycrane.com/blog/2008/06/how-to-get-current-date-and-time-in/
resulting in:
import time # import time library
import datetime # this is the way to import a module named datetime...
import pytz # imports Python time zone (needed to first do: sudo easy_install --pytz upgrade)
now = datetime.datetime.now(pytz.timezone('US/Pacific'))
timenow = now.strftime("%I:%M %p")
print timenow
if timenow > "08:30 PM" and timenow < "08:45 PM":
print "Programmed Pause"
time.sleep(999999)
This creates a time only output in your local 12 hour format with AM/PM that can be used in if statements, etc.
I am importing data from a JSON file and it has the date in the following format 1/7/11 9:15
What would be the best variable type/format to define in order to accept this date as it is? If not what would be the most efficient way to accomplish this task?
Thanks.
"What would be the best variable type/format to define in order to accept this date as it is?"
The DateTimeField.
"If not what would be the most efficient way to accomplish this task?"
You should use the datetime.strptime method from Python's builtin datetime library:
>>> from datetime import datetime
>>> import json
>>> json_datetime = "1/7/11 9:15" # still encoded as JSON
>>> py_datetime = json.loads(json_datetime) # now decoded to a Python string
>>> datetime.strptime(py_datetime, "%m/%d/%y %I:%M") # coerced into a datetime object
datetime.datetime(2011, 1, 7, 9, 15)
# Now you can save this object to a DateTimeField in a Django model.
If you take a look at https://docs.djangoproject.com/en/dev/ref/models/fields/#datetimefield, it says that django uses the python datetime library which is docomented at http://docs.python.org/2/library/datetime.html.
Here is a working example (with many debug prints and step-by-step instructions:
from datetime import datetime
json_datetime = "1/7/11 9:15"
json_date, json_time = json_datetime.split(" ")
print json_date
print json_time
day, month, year = map(int, json_date.split("/")) #maps each string in stringlist resulting from split to an int
year = 2000 + year #be ceareful here! 2 digits for a year may cause trouble!!! (could be 1911 as well)
hours, minutes = map(int, json_time.split(":"))
print day
print month
print year
my_datetime = datetime(year, month, day, hours, minutes)
print my_datetime
#Generate a json date:
new_json_style = "{0}/{1}/{2} {3}:{4}".format(my_datetime.day, my_datetime.month, my_datetime.year, my_datetime.hour, my_datetime.minute)
print new_json_style