I'm trying to convert epoch time using Python. However, the year always seems to be wrong. In the below example, it should be 2014.
import time
timestamp = time.strftime("%a, %d %b %Y %H:%M:%S +0000",
time.localtime(1415219530834))
What am I doing wrong?
I get this result:
Sat, 09 Jul 46816 16:20:34 +0000
You are passing time in milliseconds, but it should be in seconds. Divide it by 1000
import time
timestamp = time.strftime("%a, %d %b %Y %H:%M:%S +0000",
time.localtime(1415219530))
result:
'Wed, 05 Nov 2014 15:32:10 +0000'
You've passed a timestamp in milliseconds, but localtime expects a value in seconds.
time.localtime(1415219530834 / 1000)
Try this also
import datetime
datetime.datetime.fromtimestamp(your time in epoch/1000)
Convert time in epoch
int(yourtime.strftime("%s"))*1000
You are getting the Epoch in Milliseconds in Python. You need to get it in seconds for it to work correctly.
Something like
import time
mytime = 1415219530834
seconds = int(mytime/1000)
timestamp = time.strftime("%a, %d %b %Y %H:%M:%S +0000",time.localtime(seconds))
Related
I am trying to parse the mailing list of Apache Pig. I use the following function while parsing the dates.
from datetime import datetime
def str_to_date(date_str):
# First, remove the (UTC) type of parts at the end
try:
date_str = date_str[: date_str.index("(") - 1]
except ValueError:
pass
# Then, try different date formats
for date_format in [
"%a, %d %b %Y %H:%M:%S %z",
"%a %b %d %Y %H:%M:%S %z",
"%a %b %d %H:%M:%S %Y %z",
"%d %b %Y %H:%M:%S %z",
]:
try:
return datetime.strptime(date_str, date_format)
except ValueError:
pass
raise ValueError("No valid date format found for {}".format(date_str))
In the 201201.mbox, the following error raises:
ValueError: No valid date format found for Fri, 20 Jan 2012 16:31:14 +0580
When I inspect the mbox, I realized that it includes Date: Fri, 20 Jan 2012 16:31:14 +0580 line. So, it does not match any of the date formats in the function but the problem is +0580 should be "a 5-character string of the form +HHMM or -HHMM, where HH is a 2-digit string giving the number of UTC offset hours, and MM is a 2-digit string giving the number of UTC offset minutes" (docs)
According to the mbox, the offset of the mail date is +0580, which means plus 5 hours and 80 minutes. Isn't that wrong? Or, do I miss something?
There are only 60 minutes in an hour, so MM can't be more than 59. +0580 should be +0620.
When I pull events start times from Facebook Graph in comes in this form:
2017-09-26T18:00:00+0300
I'd like to convert it into readable format so I use this:
readable_event_date = dateutil.parser.parse(event_date).strftime('%a, %b %d %Y %H:%M:%S')
and it comes out like this:
Tue, 26 Sep 2017 18:00:00
Which is good but it loses the offset from UTC and I'd like it in AM PM format.
Thus, I would like it like this:
Tue, 26 Sep 2017 9:00 PM
To get into 12 hours format and keep offset from UTC for printing :
from dateutil.parser import parse
event_date = '2017-09-26T18:00:0+0300'
date = parse(event_date)
offset = date.tzinfo._offset
readable_event_date = (date + offset).strftime('%a, %b %d %Y %I:%M:%S %p')
print(readable_event_date)
Output:
'Tue, Sep 26 2017 09:00:00 PM'
It seems like what you want is this time, expressed in UTC, in the format '%a, %b %d %Y %I:%M:%S %p'. Luckily, all the information you need to do this is contained in the datetime object that you parsed, you just need to convert to UTC
Python 2.6+ or Python 3.3+:
The approach you've taken using dateutil will work for Python 2.6+ or Python 3.3.+ (and also works for a greater variety of datetime string formats):
from dateutil.parser import parse
# In Python 2.7, you need to use another one
from dateutil.tz import tzutc
UTC = tzutc()
dt_str = '2017-09-26T18:00:00+0300'
dt = parse(dt_str)
dt_utc = dt.astimezone(UTC) # Convert to UTC
print(dt_utc.strftime('%a, %b %d %Y %I:%M:%S %p'))
# Tue, Sep 26 2017 03:00:00 PM
One thing I notice is that the date you've provided, as far as I can tell, represents 3PM in UTC, not 9PM (as your example states). This is one reason you should use .astimezone(UTC) rather than some other approach.
If you want to include the time zone offset information, you can also use the %z parameter on the non-converted version of the datetime object.
print(dt.strftime('%a, %b %d %Y %I:%M:%S%z %p'))
# Tue, Sep 26 2017 06:00:00+0300 PM
This %z parameter may also be useful even if you are keeping it in UTC, because then you can at least be clear that the date the user is seeing is a UTC date.
Python 3.2+ only:
Given that you know the exact format of the input string, in Python 3.2+, you can achieve this same thing without pulling in dateutil, and it will almost certainly be faster (which may or may not be a concern for you).In your case here is how to rewrite the code so that it works with just the standard library:
from datetime import datetime, timezone
UTC = timezone.utc
dt_str = '2017-09-26T18:00:00+0300'
dt = datetime.strptime(dt_str, '%Y-%m-%dT%H:%M:%S%z')
dt_utc = dt.astimezone(UTC)
print(dt_utc.strftime('%a, %b %d %Y %I:%M:%S %p'))
# Tue, Sep 26 2017 03:00:00 PM
print(dt.strftime('%a, %b %d %Y %I:%M:%S%z %p'))
# Tue, Sep 26 2017 06:00:00+0300 PM
Have the following string:
"date Thursday June 03 12:02:56 2017"
What would be the proper way of convert it to epoch time?
You can use datetime.strptime() to parse your date and then just do delta with the epoch:
from datetime import datetime as dt
epoch = dt(1970, 1, 1)
date = "date Thursday June 03 12:02:56 2017"
epoch_time = int((dt.strptime(date, "date %A %B %d %H:%M:%S %Y") - epoch).total_seconds())
# 1496491376
Another solution is to create a time.struct_time structure by parsing with time.strptime() and then pass it into calendar.timegm() to convert to epoch time.
import time
import calendar
timestr = "date Thursday June 03 12:02:56 2017"
calendar.timegm(time.strptime(timestr, "date %A %B %d %H:%M:%S %Y"))
# returns 1496491376
I'm pulling the date value from gmail and trying to perform some functions on it. First I simply want to display it, but I can't even do that. See my code and error below.
from datetime import datetime
timeString = 'Sat, 2 Aug 2014 09:29:31 -0700'
myTime = datetime.strptime(timeString, '%m-%d-%Y %I:%M %p')
Here's the error I get. Do you think its the -0700 that's getting in the way?
ValueError: time data 'Sat, 2 Aug 2014 09:29:31 -0700' does not match format '%m-%d-%Y %I:%M %p'
As the error message suggests, you need to put the same format as your date string is in, I've not tried it, but something like this should work:
myTime = datetime.strptime(timeString, '%a, %d %b %Y %I:%M:%S %z')
Check here for complete details.
I have this date from Twitter:
created_at = "Wed Aug 29 17:12:58 +0000 2012"
I want to convert it to a time using something like:
time.mktime(created_at)
But I get this error:
TypeError: argument must be 9-item sequence, not str
What am I doing wrong?
You need to convert the incoming string to a Python time tuple using strptime before you can do anything with it.
This code will take the input string, convert it to a tuple and then converts that to a Unix-epoch time float using time.mktime:
import time
created_at = "Wed Aug 29 17:12:58 +0000 2012"
print time.mktime(time.strptime(created_at,"%a %b %d %H:%M:%S +0000 %Y"))
I don't if it too late, use arrow package instead could fewer imports and a lot less code.
pip install arrow
Then:
>>> arrow.Arrow.strptime("Wed Aug 29 17:12:58 +0000 2012", "%a %b %d %H:%M:%S %z %Y")
<Arrow [2012-08-29T17:00:58+00:00]>
>>> arrow.Arrow.strptime("Wed Aug 29 17:12:58 +0000 2012", "%a %b %d %H:%M:%S %z %Y").timestamp
1346259658
Read the documentation of time.mktime
It requires struct_time, or you can alternatively represent it using a 9-tuple.
The required entries are:
Year
Month
Date
Hour
Minute
Second
Day in week
Day in year
Daylight Savings Time
This is not the function you need, however. It seems that you want to use strptime instead.
According to the documentation:
Parse a string representing a time according to a format.
The return value is a struct_time as returned by gmtime() or localtime().
>>> import time
>>> time.strptime("30 Nov 00", "%d %b %y")
time.struct_time(tm_year=2000, tm_mon=11, tm_mday=30, tm_hour=0, tm_min=0,
tm_sec=0, tm_wday=3, tm_yday=335, tm_isdst=-1)
So, you can do:
time.strptime(created_at)