i am tring to convert this unix timestamp 1491613677888 to readable date.
found here (stackoverflow) that python script:
import datetime
print(
datetime.datetime.fromtimestamp(
int("1284101485")
).strftime('%Y-%m-%d %H:%M:%S')
)
but when i put my timestamp there, i got that error:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
OSError: [Errno 22] Invalid argument
now i see that the timestamp that i am using is 3 chars longer.
i checked it on this link:
http://www.unixtimestamp.com/index.php
and saw that its get the time out of it.
how can i do it using python?
(i am using python 3.4)
Your timestamp is not the 'classical' Unix timestamp (number of seconds since Jan 1st, 1970), as it is expressed in milliseconds.
You can translate it like this:
import datetime
timestamp_with_ms = 1491613677888
# We separate the 'ordinary' timestamp and the milliseconds
timestamp, ms = divmod(timestamp_with_ms, 1000)
#1491613677 888
# We create the datetime from the timestamp, we must add the
# milliseconds separately
dt = datetime.datetime.fromtimestamp(timestamp) + datetime.timedelta(milliseconds=ms)
formatted_time = dt.strftime('%Y-%m-%d %H:%M:%S.%f')[:-3]
# With Python 3.6, you could use:
# formatted_time = dt.isoformat(sep=' ', timespec='milliseconds')
print(formatted_time)
# 2017-04-08 03:07:57.888
Edit: I hadn't noticed that fromtimestamp accepts a float. So, we can simply do:
import datetime
timestamp_with_ms = 1491613677888
dt = datetime.datetime.fromtimestamp(timestamp_with_ms / 1000)
formatted_time = dt.strftime('%Y-%m-%d %H:%M:%S.%f')[:-3]
# With Python 3.6, you could use:
# formatted_time = dt.isoformat(sep=' ', timespec='milliseconds')
print(formatted_time)
# 2017-04-08 03:07:57.888
Your timestamp is 3 characters longer AND is a standard unix timestamp? That would mean your timestamp is at least 40,000 years into the future from today. Otherwise, the last 3 characters may represent something else, like milliseconds but that doesn't explain the error you're seeing.
If they are the milliseconds, and seeing how you're not using them in the format string, I see no harm in simply stripping them.
standard_unix_ts = int("1284101485000"[:-3])
EDIT Taking into account the comment of #cdarke, I'd suggest this instead:
standard_unix_ts = int("1284101485000"[:10])
EDIT 2 Following Gils comment
import datetime
not_unix_ts = "1284101485088"
unix_ts, milliseconds = not_unix_ts[:10], not_unix_ts[10:]
dt = datetime.datetime.fromtimestamp(float(unix_ts))
FORMAT_STRING = '%Y-%m-%d %H:%M:%S'
print("%s and %s milliseconds" % (dt.strftime(FORMAT_STRING), milliseconds))
Related
I have to read a JSON file and It has the date fields formated like this below
"MyDate": "/Date(1603284014088)/",
I found some examples to parse it in other languages (JavaScript, Kotlin) but nothing in Python.
I could find on this SCOTT HANSELMAN's post here that they are milliseconds since the beginning of the Unix Epoch sometimes with a TimeZone. So I could write a simple function to decode it.
import re
from datetime import datetime, timedelta
def decode_date (encoded_date):
mask = "\/Date\(([0-9]*)\)"
offset = datetime(1970, 1, 1)
my_matchs = re.match(mask, encoded_date).groups()
if len(my_matchs) == 1:
return datetime(1970, 1, 1) + timedelta(milliseconds=int(my_matchs[0]))
else:
return None
encoded = "/Date(1603284014088)/"
print (decode_date(encoded))
This function can't parse dates with timezone because I'm lazy :), My question is - is there some lib that can parse it out of the box in Python?
Given the fact that you are already able to extract the date using RegEx please try the following code for conversion:
import datetime
s = '1603284014088'
fmt = "%Y-%m-%d %H:%M:%S"
# Local time
t = datetime.datetime.fromtimestamp(float(s)/1000.)
print (t.strftime(fmt))
# UTC time
t_utc = datetime.datetime.utcfromtimestamp(float(s)/1000.)
print (t_utc.strftime(fmt))
I am getting a response from the rest is an Epoch time format like
start_time = 1234566
end_time = 1234578
I want to convert that epoch seconds in MySQL format time so that I could store the differences in my MySQL database.
I tried:
>>> import time
>>> time.gmtime(123456)
time.struct_time(tm_year=1970, tm_mon=1, tm_mday=2, tm_hour=10, tm_min=17, tm_sec=36, tm_wday=4, tm_yday=2, tm_isdst=0)
The above result is not what I am expecting. I want it be like
2012-09-12 21:00:00
Please suggest how can I achieve this?
Also,
Why I am getting TypeError: a float is required for
>>> getbbb_class.end_time = 1347516459425
>>> mend = time.gmtime(getbbb_class.end_time).tm_hour
Traceback (most recent call last):
...
TypeError: a float is required
To convert your time value (float or int) to a formatted string, use:
import time
time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(1347517370))
For example:
import time
my_time = time.strftime('%Y-%m-%d %H:%M:%S', time.localtime(1347517370))
print(my_time)
You can also use datetime:
>>> import datetime
>>> datetime.datetime.fromtimestamp(1347517370).strftime('%c')
'2012-09-13 02:22:50'
>>> import datetime
>>> datetime.datetime.fromtimestamp(1347517370).strftime('%Y-%m-%d %H:%M:%S')
'2012-09-13 14:22:50' # Local time
To get UTC:
>>> datetime.datetime.utcfromtimestamp(1347517370).strftime('%Y-%m-%d %H:%M:%S')
'2012-09-13 06:22:50'
This is what you need
In [1]: time.time()
Out[1]: 1347517739.44904
In [2]: time.strftime("%Y-%m-%d %H:%M:%S", time.gmtime(time.time()))
Out[2]: '2012-09-13 06:31:43'
Please input a float instead of an int and that other TypeError should go away.
mend = time.gmtime(float(getbbb_class.end_time)).tm_hour
Try this:
>>> import time
>>> time.strftime("%Y-%m-%d %H:%M:%S", time.gmtime(1347517119))
'2012-09-12 23:18:39'
Also in MySQL, you can FROM_UNIXTIME like:
INSERT INTO tblname VALUES (FROM_UNIXTIME(1347517119))
For your 2nd question, it is probably because getbbb_class.end_time is a string. You can convert it to numeric like: float(getbbb_class.end_time)
If you have epoch in milliseconds a possible solution is convert to seconds:
import time
time.ctime(milliseconds/1000)
For more time functions: https://docs.python.org/3/library/time.html#functions
#This adds 10 seconds from now.
from datetime import datetime
import commands
date_string_command="date +%s"
utc = commands.getoutput(date_string_command)
a_date=datetime.fromtimestamp(float(int(utc))).strftime('%Y-%m-%d %H:%M:%S')
print('a_date:'+a_date)
utc = int(utc)+10
b_date=datetime.fromtimestamp(float(utc)).strftime('%Y-%m-%d %H:%M:%S')
print('b_date:'+b_date)
This is a little more wordy but it comes from date command in unix.
First a bit of info in epoch from man gmtime
The ctime(), gmtime() and localtime() functions all take an argument of data type time_t which represents calendar time. When inter-
preted as an absolute time value, it represents the number of seconds elapsed since 00:00:00 on January 1, 1970, Coordinated Universal
Time (UTC).
to understand how epoch should be.
>>> time.time()
1347517171.6514659
>>> time.gmtime(time.time())
(2012, 9, 13, 6, 19, 34, 3, 257, 0)
just ensure the arg you are passing to time.gmtime() is integer.
Sharing an answer to clearly distinguish UTC and local time conversions. Use import datetime at the top before using the below methods.
Convert to datetime of local machine's timezone
datetime.datetime.fromtimestamp(1347517370)
Convert to datetime of UTC timezone
datetime.datetime.utcfromtimestamp(1347517370)
For both the above methods, if you wish to return a formatted date string, use the following code block
datetime.datetime.fromtimestamp(1347517370).strftime('%Y-%m-%d %H:%M:%S')
datetime.datetime.utcfromtimestamp(1347517370).strftime('%Y-%m-%d %H:%M:%S')
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 have spent some time trying to figure out how to get a time delta between time values. The only issue is that one of the times was stored in a file. So I have one string which is in essence str(datetime.datetime.now()) and datetime.datetime.now().
Specifically, I am having issues getting a delta because one of the objects is a datetime object and the other is a string.
I think the answer is that I need to get the string back in a datetime object for the delta to work.
I have looked at some of the other Stack Overflow questions relating to this including the following:
Python - Date & Time Comparison using timestamps, timedelta
Comparing a time delta in python
Convert string into datetime.time object
Converting string into datetime
Example code is as follows:
f = open('date.txt', 'r+')
line = f.readline()
date = line[:26]
now = datetime.datetime.now()
then = time.strptime(date)
delta = now - then # This does not work
Can anyone tell me where I am going wrong?
For reference, the first 26 characters are acquired from the first line of the file because this is how I am storing time e.g.
f.write(str(datetime.datetime.now())
Which would write the following:
2014-01-05 13:09:42.348000
time.strptime returns a struct_time.
datetime.datetime.now() returns a datetime object.
The two can not be subtracted directly.
Instead of time.strptime you could use datetime.datetime.strptime, which returns a datetime object. Then you could subtract now and then.
For example,
import datetime as DT
now = DT.datetime.now()
then = DT.datetime.strptime('2014-1-2', '%Y-%m-%d')
delta = now - then
print(delta)
# 3 days, 8:17:14.428035
By the way, you need to supply a date format string to time.strptime or DT.datetime.strptime.
time.strptime(date)
should have raised a ValueError.
It looks like your date string is 26 characters long. That might mean you have a date string like 'Fri, 10 Jun 2011 11:04:17 '.
If that is true, you may want to parse it like this:
then = DT.datetime.strptime('Fri, 10 Jun 2011 11:04:17 '.strip(), "%a, %d %b %Y %H:%M:%S")
print(then)
# 2011-06-10 11:04:17
There is a table describing the available directives (like %Y, %m, etc.) here.
Try this:
import time
import datetime
d = datetime.datetime.now()
now = time.mktime(d.timetuple())
And then apply the delta
if you have the year,month,day of 'then' you may use:
year = 2013
month = 1
day = 1
now_date = datetime.datetime.now()
then_date = now_date.replace(year = year, month = month, day = day)
delta = now_date - then_date
I have a datetime object with integer number of seconds (ex: 2010-04-16 16:51:23). I am using the following command to extract exact time
dt = datetime.datetime.strptime(time, '%Y-%m-%d %H:%M:%S.%f
(generically, I have decimals (ex: 2010-04-16 16:51:23.1456) but sometimes I don't. So when I run this command, I get an error message
ValueError: time data '2010-04-16 16:51:23' does not match format '%Y-%m-%d %H:%M:%S.%f'
How do I go about resolving this?
It's because you don't have the format you specified. You have the format:
'%Y-%m-%d %H:%M:%S'
There are multiple solutions. First, always generate the data in the same format (adding .00 if you need to).
A second solution is that you try to decode in one format and if you fail, you decode using the other format:
try:
dt = datetime.datetime.strptime(time, '%Y-%m-%d %H:%M:%S.%f')
except ValueError:
dt = datetime.datetime.strptime(time, '%Y-%m-%d %H:%M:%S')
Another way avoiding using the exception handling mechanism is to default the field if not present and just try processing with the one format string:
from datetime import datetime
s = '2010-04-16 16:51:23.123'
dt, secs = s.partition('.')[::2]
print datetime.strptime('{}.{}'.format(dt, secs or '0'), '%Y-%m-%d %H:%M:%S.%f')
if you're using the latest python (3.2+) simple-date will do this kind of thing for you:
>>> from simpledate import *
>>> SimpleDate('2010-04-16 16:51:23.1456')
SimpleDate('2010-04-16 16:51:23.145600', tz='America/Santiago')
>>> SimpleDate('2010-04-16 16:51:23')
SimpleDate('2010-04-16 16:51:23', tz='America/Santiago')
it works by extending the python template format. so you could also write (it's not needed because ISO8601-like formats are handled by default):
>>> SimpleDate('2010-04-16 16:51:23', format='Y-m-d H:M:S(.f)?')
SimpleDate('2010-04-16 16:51:23', tz='America/Santiago')
see how the fractional seconds are (.f)? like a regexp - means it's optional (also, it will add % signs if there are none).
PS and you can access the datetime via an attribute. if you wanted to discard the tzinfo (which is taken from the locale by default - i live in chile, hence America/Santiago above) to get a naive datetime:
>>> SimpleDate('2010-04-16 16:51:23').naive.datetime
datetime.datetime(2010, 4, 16, 16, 51, 23)