having issues with python time object - python

i am having a small program that gets time from system and dose some arithemetic on it.
here is my code:
import time
import datetime
c_time = time.strftime("%H:%M;%S")
# now to convert it into time object i am using
c_time_converted = datetime.datetime.strptime(c_time,"%H:%M;%S")
print c_time_converted
the output is of the form :
1900-01-01 11:39:40
but i want only the time part when i split and perform other operations on it i get a string returned but i need in time format so that i can perform time arethemetic
i want it in form 11: 39:40

Just use .time():
from datetime import datetime
c_time = '2015-06-08 23:13:57'
c_time_converted = datetime.strptime(c_time,"%Y-%m-%d %H:%M:%S")
print c_time_converted
print c_time_converted.time()
prints:
2015-06-08 23:13:57
23:13:57
EDIT (addressing a comment regarding datetime)
Here is a simple example of using a difference in datetime:
from datetime import timedelta
c_time_later = '2015-06-08 23:50:21'
c_time_later_converted = datetime.strptime(c_time_later,"%Y-%m-%d %H:%M:%S")
dt = c_time_later_converted - c_time_converted
print dt # time I was away from stackoverflow
prints: 0:36:24
now we will add dt time back to c_time above and see that we recover c_time_later:
print (c_time_converted + dt).time()
prints: 23:50:21
Or add an hour using timedelta:
print (c_time_converted + timedelta(hours=1)).time() # prints 00:13:57

I made a minor change in your code. Please check. it will give you time only.
import time
import datetime
c_time = time.strftime("%H:%M:%S")
# now to convert it into time object i am using
c_time_converted = datetime.datetime.strptime(c_time,"%H:%M:%S")
print c_time_converted.time()

Try to this.
import time
import datetime
c_time = time.strftime("%H:%M;%S")
c_time_converted = datetime.datetime.strptime(c_time,"%H:%M;%S")
print c_time_converted.time()
Output :
12:04:31
Get Current Date and Time.
from datetime import datetime
print datetime.now().strftime('%Y-%m-%d %H:%M:%S')
Output:
2015-06-09 12:09:09

Related

Convert datetime object into a string

I need to convert a datetime into a string using numpy.
Is there another way to directly convert only one object to string that doesn't involve using the following function passing an array of 1 element (which returns an array too)?
numpy.datetime_as_string(arr, unit=None, timezone='naive', casting='same_kind')
With this function, I can make the conversion, but I just want to know if there is a more direct/clean way to do it.
Thanks in advance.
As we dont know what is inside of arr, I assume it is just datetime.now()
If so try this:
import datetime
datetime.datetime.now().strftime('%Y-%m-%d %H:%M:%S.%f')
>>> '2022-07-28 10:27:34.986848'
If you need numpy version:
np.array(datetime.datetime.now(), dtype='datetime64[s]')
>>> array('2022-07-28T10:32:19', dtype='datetime64[s]')
if you just want to convert one numpy DateTime64 object into a string, here is the answer.
import datetime
yourdt = yourdt.astype(datetime.datetime)
yourdt_str = yourdt.strftime("%Y-%m-%d %H:%M:%S")
that's it
from datetime import datetime
now = datetime.now() # current date and time
year = now.strftime("%Y")
print("year:", year)
month = now.strftime("%m")
print("month:", month)
day = now.strftime("%d")
print("day:", day)
time = now.strftime("%H:%M:%S")
print("time:", time)
date_time = now.strftime("%m/%d/%Y, %H:%M:%S")
print("date and time:",date_time)

Unable to convert a string to a datetime object in python and perform some time related calculations with it

What I am trying to do is to get the current datetime of a place using an API with python and extract datetime from it. The code that I have is:
import requests
import json
from datetime import datetime
import time
def get_current_time_from_api():
response = (requests.get("http://worldtimeapi.org/api/ip")).json()
return response["datetime"]
the_time = get_current_time_from_api()
When I print the response using print(the_time), the response that gets returned is:
2020-05-06T10:04:51.368291+05:45
Then, I tried getting the converting the string to datetime using the function datetime.strptime(the_time, "%X) to get the time, I get the error ValueError: time data '2020-05-06T10:09:52.009222+05:45' does not match format '%X' So, what went wrong and how can I do things like this when the time is parsed from the string?
if(time == "10:00:00 pm"):
#do something here
else:
difference_in_minutes = "10:00:00" - current_time
time.sleep(difference_in_minutes * 100) #sleeping for that many seconds
#do stuff when the time is 10 pm
I think you may be looking for the fromisoformat method. Try this:
import datetime as dt
dt.datetime.fromisoformat(the_time).strftime('%X')
Output:
'21:37:54'
from datetime import datetime
from dateutil.relativedelta import relativedelta
datetime_obj = datetime.strptime(
'2020-05-06T10:04:51.368291+05:45', # your datetime string
'%Y-%m-%dT%H:%M:%S.%f%z' # format of datetime
)
# this is how you can add a day to date_object
new_date = datetime_obj + relativedelta(days=1)
This is wrong time == "10:00:00 pm"
you should use datetime_objects to compare, like:
if new_date > datetime_obj: # this is true.
# You can do things here
print("Yes")
# if(time == "10:00:00 pm"), should be done like this:
if datetime_obj.time().hour == 10 and datetime_obj.time().min == 10:
pass
See for datetime formatting :
https://docs.python.org/3/library/datetime.html#strftime-and-strptime-format-codes
relativedelta:
https://dateutil.readthedocs.io/en/stable/relativedelta.html

Extract only time (HH:MM) from datetime field - Odoo 10

I'a m trying to extract only time (Hour:Minute) from datetime field
Example:
today_with_hour = fields.Datetime(
string=u'hora',
default=fields.Datetime.now,
)
I would like to know how get only hour from today_with_hour in format
17:10:20
This is one way to extract:
from datetime import datetime
now = datetime.now()
print(str(now.hour)+':'+str(now.minute)+':'+str(now.second))
This may be better way to do it
You can use strftime
Example:
from datetime import datetime
datetime.now().strftime("%H:%M:%S")
In your case you can follow like this:
from datetime import datetime
datetime.strptime('20/06/2019 17:28:52', "%d/%m/%Y %H:%M:%S").time()
Output will be:
17:28:52
Better way to do is by using strftime().
dt = datetime.strptime('20/06/2019 17:28:52', "%d/%m/%Y %H:%M:%S")
dt.strftime("%H:%M:%S")
output:
17:28:52
To get the current time from the datetime.now()
datetime.datetime.now().time().strftime("%H:%M:%S")
O/P:
'11:16:17'
if you want to get the time with milliseconds also, use isoformat()
datetime.datetime.now().time().isoformat()
O/P:
'11:20:34.978272'

Convert local time to UNIX

I'm new to python and I'm trying to get the actual minutes passed every day since 7:00.
I am using mktime to get now_date1 and now_date2 in seconds, and then the plan it's to subtract and divide by 60 to get the minutes.
But I get the following error:
AttributeError: 'str' object has no attribute 'timetuple'
It's this the correct approach?
Here it's the code
import time
import pytz
from datetime import datetime
from time import mktime as mktime
now_date = datetime.now(pytz.timezone('Europe/Bucharest'))
now_date1 = now_date.strftime('%H:%M:%S')
now_date2 = now_date.strftime('7:00:00')
# Convert to Unix timestamp
d1_ts = time.mktime(now_date1.timetuple())
strftime returns a string. Not what you want.
You were pretty close, but there's no need to put time in the mix. Just modify your code like this and use time delta from datetime (inspired by How to calculate the time interval between two time strings):
import pytz
from datetime import datetime
now_date = datetime.now(pytz.timezone('Europe/Bucharest'))
from datetime import datetime
FMT = '%H:%M:%S'
now_date1 = now_date.strftime(FMT)
now_date2 = now_date.strftime('7:00:00')
tdelta = datetime.strptime(now_date1, FMT) - datetime.strptime(now_date2, FMT)
print(tdelta)
I get: 6:40:42 which seems to match since it's 12:42 here.
To get the result in minutes just do:
tdelta.seconds//60
(note that the dates have only correct hour/time/seconds, the year, month, etc.. are 1900 ... since they're not used)
I think something like this might work:
import time
import datetime
from time import mktime as mktime
#current time
now_date = datetime.datetime.now()
#time at 7am
today = datetime.date.today()
now_date2 = datetime.datetime(today.year, today.month, today.day, 7, 0, 0, 0)
#difference in minutes
(now_date - now_date2).days * 24 * 60

Get time regardless of the Timezone/DST in python using datetime

I have the following string in python:
message = "2015-08-26T19:30:00+0200"
And I want to retrieve the time from it so I used:
import pandas as pd
import datetime
date=pd.to_datetime(message)
m=datetime.time(date)
The output is
17:30:00
How can I get 19:30 regardless of the DST
I used the strptime with the %z format and it worked
import datetime
message = "2015-08-26T19:30:00+0200"
fmt = '%Y-%m-%dT%H:%M:%S%z'
d=datetime.datetime.strptime(message, fmt)
print(d.time())
Using arrow:
import arrow
message = "2015-08-26T19:30:00+0200"
m = arrow.get(message, 'YYYY-MM-DDTHH:mm:ssZ')
print m.format('YYYY-MM-DDTHH:mm:ssZ') # 2015-08-26T19:30:00+0200
print m.format('HH:mm:ss') # 19:30:00
Information about arrow is at http://crsmithdev.com/arrow/.

Categories

Resources