Convert string datetime format into integer time in seconds in python - python-2.7

My input is input_time = "May 5 2016 11:29:32".
Expected output should be in seconds or milli seconds which is type of integer i.e., output_time = 2424241313113.
The above conversion should be done in python. How to do this conversion?

Here's how to convert date time into epoch seconds (dated starting from 00:00:00 UTC on 1 January 1970)
In Python 3.3+
from datetime import datetime
datetime.strptime('May 5 2016 11:29:32','%b %d %Y %H:%M:%S').timestamp()
In Python 2.7.9
datetime.strptime('May 5 2016 11:29:32','%b %d %Y %H:%M:%S').strftime('%s')
Note that strftime('%s') use your local time zone.

Related

Why my Python timestamp to datetime conversion is wrong?

Portal epochconverter.com converts timestamp 1531423084013 to correct date of Thursday, July 12, 2018 3:18:04.013 PM GMT-04:00 DST. But in Python 2.7.12 I got below which is wrong
>>> timestamp=1531423084013
>>> time.ctime(timestamp).rsplit(' ', 1)[0]
'Wed Nov 12 00:06:53'
How to make it correct ?
1531423084013 is in milliseconds not is seconds.
As you can see from epochconverter.com the hour is : 3:18:04.013, so the seconds part is 4.013, this site handle time in seconds and in milliseconds (it seems when the input has 13 digits instead of 10 for time around nowadays).
But time.ctime() from python handle only time in seconds and this is why you get a wrong answer when you enter a time in milliseconds (in my system it throws an out of range).
So you must divide your time in milliseconds by 1000 :
time.ctime(1531423084)
'Thu Jul 12 21:18:04 2018'
(My time zone is UTC+0200)

Regex - Slice Date - Aug 22, 2017 02:00 PM EDT

I'm trying to take a date, for example Aug 22, 2017 02:00 PM EDT
and get the month, day, year from it.
month = re.findall(r'', date)[0]
day = re.findall(r'', date)[0]
year = re.findall(r'', date)[0]
I've started with something like this:
(.*)(?<=[a-zA-Z]{3}\s)
for the month. Is there a better way to do this?
You need to first convert to datetime and then extract the needed values like this (reusing the example):
from datetime import datetime
datetime_object = datetime.strptime('Jun 1 2005 1:33PM', '%b %d %Y %I:%M%p')
print(datetime_object.year, datetime_object.month, datetime_object.day)
From what I can see you probably won't need to specify the format but pass the string directly to the datetime.strptime function.

How to print the current time in the format Day, Date Month Year HH:MM:SS?

How to print the current time in the format Day, Date Month Year HH:MM:SS
Mon, 28 Aug 2017 15:37:01 .
And then, convert this timestamp to epoch seconds & vice-versa.
datetime module does all the job
>>> import datetime
>>> datetime.datetime.now().strftime("%a, %d %B %Y %H:%M:%S")
'Tue, 29 August 2017 03:04:21'

Converting '4 days ago' etc. to the actual dates

I have a massive spreadsheet in which all dates are written this way:
2 days ago
9 days ago
34 days ago
54 days ago
etc.
Is there a clever Python way to convert these data to the actual dates, if I tell Python what date '1 day ago' is?
Use timedelta.
Extract the value from that string in your spreadsheet and then use
d = date.today() - timedelta(days_to_subtract)
If the input date format may slightly vary (human input) then you could use parsedatetime module to parse human-readable date/time text into datetime objects:
#!/usr/bin/env python
import sys
from datetime import datetime
import parsedatetime # $ pip install parsedatetime
now = datetime(2015, 3, 8) # the reference date
cal = parsedatetime.Calendar()
for line in sys.stdin: # at most one date per line
dt, type = cal.parseDT(line, now)
if type > 0:
print(dt)
Output
2015-03-06 00:00:00
2015-02-27 00:00:00
2015-02-02 00:00:00
2015-01-13 00:00:00

Finding difference between string time objects in python

I have a list of strings that I am reading from a file - Each of the strings has a time offset that was recorded while storing the data.
date1= "Mon May 05 20:00:00 EDT 2014"
date2="Mon Nov 18 19:00:00 EST 2013"
date3="Mon Nov 07 19:00:00 PST 2013"
I need to find the difference in days between each pair of strings.
from datetime import datetime
from dateutil import tz
def days_hours_minutes(td):
return td.days, td.seconds//3600, (td.seconds//60)%60
date1='Fri Dec 05 19:00:00 2014' # it does not work with EDT, EST etc.
date2='Fri Dec 03 19:00:00 2014'
fmt = "%a %b %d %H:%M:%S %Y"
str1 = datetime.strptime(date1, fmt)
str2 = datetime.strptime(date2, fmt)
td=(str1-str2)
x=days_hours_minutes(td)
print x
#gives (2, 0, 0)
Basically, convert each string to its "my_time_obj" and then take the difference in days.
However, my actual string dates, have "EDT", "EST", "IST" etc - and on using the %Z notation, I get the ValueError: time data 'Fri Dec 05 19:00:00 EST 2014' does not match format '%a %b %d %H:%M:%S %Z %Y'
from the datetime documentation, I see that I can use %Z to convert this to a timezone notation - what am I missing ?
https://docs.python.org/2/library/datetime.html
I would go with parsing the timezone using pytz and do something like this (given that you know how your date string is built):
from datetime import datetime
from dateutil import tz
from pytz import timezone
def days_hours_minutes(td):
return td.days, td.seconds//3600, (td.seconds//60)%60
date1_str ='Fri Dec 05 19:00:00 2014 EST'
date2_str ='Fri Dec 03 19:00:00 2014 UTC'
fmt = "%a %b %d %H:%M:%S %Y"
date1_list = date1_str.split(' ')
date2_list = date1_str.split(' ')
date1_tz = timezone(date1_list[-1]) # get only the timezone without date parts for date 1
date2_tz = timezone(date2_list[-1]) # get only the timezone without date parts for date 2
date1 = date1_tz.localize(datetime.strptime(' '.join(date1_list[:-1]), fmt)) # get only the date parts without timezone for date 1
date2 = date2_tz.localize(datetime.strptime(' '.join(date2_list[:-1]), fmt)) # get only the date parts without timezone for date 2
td=(date1-date2)
x=days_hours_minutes(td)
print x
Converting time strings to POSIX timestamps and finding the differences using only stdlib:
#!/usr/bin/env python
from datetime import timedelta
from email.utils import parsedate_tz, mktime_tz
dates = [
"Mon May 05 20:00:00 EDT 2014",
"Mon Nov 18 19:00:00 EST 2013",
"Mon Nov 07 19:00:00 PST 2013",
]
ts = [mktime_tz(parsedate_tz(s)) for s in dates] # timestamps
differences = [timedelta(seconds=a - b) for a, b in zip(ts, ts[1:])]
print("\n".join(map(str, differences)))
Read the above links about the inherit ambiguity of the input. If you want a more robust solution; you have to use explicit pytz timezones such as 'America/New_York' or else email module hardcodes "timezone abbr. to utc offset" mapping e.g., EDT -> -0400, EST -> -0500, PST -> -0800.
Output
168 days, 0:00:00
10 days, 21:00:00
differences is a list of timedelta objects, you could get full days using td.days attribute (for non-negative intervals) or to get the value including fractions:
days = td.total_seconds() / 86400