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
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'
I have a string representing a unix timestamp (i.e. "1284101485") in Python, and I'd like to convert it to a readable date. When I use time.strftime, I get a TypeError:
>>>import time
>>>print time.strftime("%B %d %Y", "1284101485")
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: argument must be 9-item sequence, not str
Use datetime module:
from datetime import datetime
ts = int('1284101485')
# if you encounter a "year is out of range" error the timestamp
# may be in milliseconds, try `ts /= 1000` in that case
print(datetime.utcfromtimestamp(ts).strftime('%Y-%m-%d %H:%M:%S'))
>>> from datetime import datetime
>>> datetime.fromtimestamp(1172969203.1)
datetime.datetime(2007, 3, 4, 0, 46, 43, 100000)
Taken from http://seehuhn.de/pages/pdate
The most voted answer suggests using fromtimestamp which is error prone since it uses the local timezone. To avoid issues a better approach is to use UTC:
datetime.datetime.utcfromtimestamp(posix_time).strftime('%Y-%m-%dT%H:%M:%SZ')
Where posix_time is the Posix epoch time you want to convert
>>> import time
>>> time.ctime(int("1284101485"))
'Fri Sep 10 16:51:25 2010'
>>> time.strftime("%D %H:%M", time.localtime(int("1284101485")))
'09/10/10 16:51'
There are two parts:
Convert the unix timestamp ("seconds since epoch") to the local time
Display the local time in the desired format.
A portable way to get the local time that works even if the local time zone had a different utc offset in the past and python has no access to the tz database is to use a pytz timezone:
#!/usr/bin/env python
from datetime import datetime
import tzlocal # $ pip install tzlocal
unix_timestamp = float("1284101485")
local_timezone = tzlocal.get_localzone() # get pytz timezone
local_time = datetime.fromtimestamp(unix_timestamp, local_timezone)
To display it, you could use any time format that is supported by your system e.g.:
print(local_time.strftime("%Y-%m-%d %H:%M:%S.%f%z (%Z)"))
print(local_time.strftime("%B %d %Y")) # print date in your format
If you do not need a local time, to get a readable UTC time instead:
utc_time = datetime.utcfromtimestamp(unix_timestamp)
print(utc_time.strftime("%Y-%m-%d %H:%M:%S.%f+00:00 (UTC)"))
If you don't care about the timezone issues that might affect what date is returned or if python has access to the tz database on your system:
local_time = datetime.fromtimestamp(unix_timestamp)
print(local_time.strftime("%Y-%m-%d %H:%M:%S.%f"))
On Python 3, you could get a timezone-aware datetime using only stdlib (the UTC offset may be wrong if python has no access to the tz database on your system e.g., on Windows):
#!/usr/bin/env python3
from datetime import datetime, timezone
utc_time = datetime.fromtimestamp(unix_timestamp, timezone.utc)
local_time = utc_time.astimezone()
print(local_time.strftime("%Y-%m-%d %H:%M:%S.%f%z (%Z)"))
Functions from the time module are thin wrappers around the corresponding C API and therefore they may be less portable than the corresponding datetime methods otherwise you could use them too:
#!/usr/bin/env python
import time
unix_timestamp = int("1284101485")
utc_time = time.gmtime(unix_timestamp)
local_time = time.localtime(unix_timestamp)
print(time.strftime("%Y-%m-%d %H:%M:%S", local_time))
print(time.strftime("%Y-%m-%d %H:%M:%S+00:00 (UTC)", utc_time))
In Python 3.6+:
import datetime
timestamp = 1642445213
value = datetime.datetime.fromtimestamp(timestamp)
print(f"{value:%Y-%m-%d %H:%M:%S}")
Output (local time)
2022-01-17 20:46:53
Explanation
Line #1: Import datetime library.
Line #2: Unix time which is seconds since 1970-01-01.
Line #3: Converts this to a unix time object, check with: type(value)
Line #4: Prints in the same format as strp. Local time. To print in UTC see example below.
Bonus
To save the date to a string then print it, use this:
my_date = f"{value:%Y-%m-%d %H:%M:%S}"
print(my_date)
To output in UTC:
value = datetime.datetime.fromtimestamp(timestamp, tz=datetime.timezone.utc)
# 2022-01-17 18:50:52
Other than using time/datetime package, pandas can also be used to solve the same problem.Here is how we can use pandas to convert timestamp to readable date:
Timestamps can be in two formats:
13 digits(milliseconds) -
To convert milliseconds to date, use:
import pandas
result_ms=pandas.to_datetime('1493530261000',unit='ms')
str(result_ms)
Output: '2017-04-30 05:31:01'
10 digits(seconds) -
To convert seconds to date, use:
import pandas
result_s=pandas.to_datetime('1493530261',unit='s')
str(result_s)
Output: '2017-04-30 05:31:01'
For a human readable timestamp from a UNIX timestamp, I have used this in scripts before:
import os, datetime
datetime.datetime.fromtimestamp(float(os.path.getmtime("FILE"))).strftime("%B %d, %Y")
Output:
'December 26, 2012'
You can convert the current time like this
t=datetime.fromtimestamp(time.time())
t.strftime('%Y-%m-%d')
'2012-03-07'
To convert a date in string to different formats.
import datetime,time
def createDateObject(str_date,strFormat="%Y-%m-%d"):
timeStamp = time.mktime(time.strptime(str_date,strFormat))
return datetime.datetime.fromtimestamp(timeStamp)
def FormatDate(objectDate,strFormat="%Y-%m-%d"):
return objectDate.strftime(strFormat)
Usage
=====
o=createDateObject('2013-03-03')
print FormatDate(o,'%d-%m-%Y')
Output 03-03-2013
timestamp ="124542124"
value = datetime.datetime.fromtimestamp(timestamp)
exct_time = value.strftime('%d %B %Y %H:%M:%S')
Get the readable date from timestamp with time also, also you can change the format of the date.
Note that utcfromtimestamp can lead to unexpected results since it returns a naive datetime object. Python treats naive datetime as local time - while UNIX time refers to UTC.
This ambiguity can be avoided by setting the tz argument in fromtimestamp:
from datetime import datetime, timezone
dtobj = datetime.fromtimestamp(1284101485, timezone.utc)
>>> print(repr(dtobj))
datetime.datetime(2010, 9, 10, 6, 51, 25, tzinfo=datetime.timezone.utc)
Now you can format to string, e.g. an ISO8601 compliant format:
>>> print(dtobj.isoformat(timespec='milliseconds').replace('+00:00', 'Z'))
2010-09-10T06:51:25.000Z
Use the following codes, I hope it will solve your problem.
import datetime as dt
print(dt.datetime.fromtimestamp(int("1284101485")).strftime('%Y-%m-%d %H:%M:%S'))
Use datetime.strftime(format):
from datetime import datetime
unixtime = int('1284101485')
# Print with local time
print(datetime.fromtimestamp(unixtime).strftime('%Y-%m-%d %H:%M:%S'))
# Print with UTC time
print(datetime.utcfromtimestamp(unixtime).strftime('%Y-%m-%d %H:%M:%S'))
datetime.fromtimestamp(timestamp): Return the local date corresponding to the POSIX timestamp, such as is returned by time.time().
datetime.utcfromtimestamp(timestamp): Return the UTC datetime corresponding to the POSIX timestamp, with tzinfo None. (The resulting object is naive.)
import datetime
temp = datetime.datetime.fromtimestamp(1386181800).strftime('%Y-%m-%d %H:%M:%S')
print temp
Another way that this can be done using gmtime and format function;
from time import gmtime
print('{}-{}-{} {}:{}:{}'.format(*gmtime(1538654264.703337)))
Output: 2018-10-4 11:57:44
If you are working with a dataframe and do not want the series cannot be converted to class int error. Use the code below.
new_df= pd.to_datetime(df_new['time'], unit='s')
i just successfully used:
>>> type(tstamp)
pandas.tslib.Timestamp
>>> newDt = tstamp.date()
>>> type(newDt)
datetime.date
You can use easy_date to make it easy:
import date_converter
my_date_string = date_converter.timestamp_to_string(1284101485, "%B %d, %Y")
quick and dirty one liner:
'-'.join(str(x) for x in list(tuple(datetime.datetime.now().timetuple())[:6]))
'2013-5-5-1-9-43'
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