Datetime format problems - python-2.7

I'm having problems converting a dateTime from one format to another.
Mon 13 Jun 2016 10:00
should become
13/06/2016 10:00:00
However, I'm having problems with the hours minutes & seconds (Yes I realise the seconds are not supplied - so that might be causing formatting problems)
Here's what I've got so far:
#!/usr/bin/env python
import datetime
def convertDateString(s):
d = datetime.datetime.strptime(s, "%a %d %b %Y")
# return "{dt.day}/{dt:%m}/{dt.year}".format(dt = datetime.date(d.year, d.month, d.day)) # no time, but works fine
return "{dt.day}/{dt:%m}/{dt.year} {dt:%H}:{dt:%M}:{dt:%S}".format(dt = datetime.date(d.year, d.month, d.day))
# print convertDateString("Mon 13 Jun 2016") # works fine, but ignores time
print convertDateString("Mon 13 Jun 2016 10:00:00")
which gives ValueError: unconverted data remains: 10:00:00
Can someone please point out where am I going wrong?

I figured it out !
# Mon 13 Jun 2016 10:00 # in
# 13/6/2016 10:00:00 # out
d = datetime.datetime.strptime(s, "%a %d %b %Y %H:%M")
return d.strftime("%d/%m/%Y %H:%M:%S")

Related

Read Javascript date input in Django

I have a calendar/datepicker done in Javascript that creates an input of the following format "Thu Mar 29 2018"
On submit, I want to read the date in a Django date field, but it fails.
What solutions do I have ?
Use datetime.strptime
In your case
from datetime import datetime
datetime_format = "%a %b %d %Y"
date_object = datetime.strptime("Thu Mar 29 2018", datetime_format)

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'

How to convert string date 11:01 PM - 11 Aug 2009 dateTime object - Python 3

Im trying to convert a string date "11:01 PM - 11 Aug 2009" into a datetime object in python. My code is:
from datetime import datetime
datetime.strptime('11:01 PM - 11 Aug 2009', '%I:%M %p - %d %B %Y')
but I am getting an error: time data '11:01 PM - 11 Aug 2009' does not match format '%I:%M %p - %d %B %Y'
Not sure what I've missed.
the issue was the month is short form so sept instead of september. Had to change it to be %b instead of %B.
Updated code is:
from datetime import datetime
datetime.strptime('11:01 PM - 11 Aug 2009', '%I:%M %p - %d %b %Y')
Use the following:
datetime.strptime('11:01 PM - 11 Aug 2009', '%I:%M %p - %d %b %Y')
%b Month as locale’s abbreviated name.
Jan, Feb, ..., Dec (en_US);
Jan, Feb, ..., Dez (de_DE)
For reference:
https://docs.python.org/3.5/library/datetime.html#strftime-and-strptime-behavior

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

Date parsing and formating in Python 2.7

I'm looking to do what may seem like an easy task but I find it to be an awful nightmare in Python 2.7.
I have a date string such as Sat, 13 Dec 2014 13:52:00 -0500 to Dec 13 2014, 13:52 am EST
Any idea how I could achieve this, preferably without doing to much coding and logic implementation, but rather using a built in functionality or a popular 3rd party lib?
Note: my timezone is not EST.
The closest I've come to is:
import time
import email.utils
observationTime = email.utils.parsedate('Sat, 13 Dec 2014 13:52:00 -0500')
print time.strftime('%b %d %Y %H:%M %p %Z', observationTime)
But it produces:
Dec 13 2014 13:52 PM GMT Daylight Time
You could use dateutil to parse the date string into a timezone-aware datetime:
import dateutil.parser as DP
observationTime = DP.parse('Sat, 13 Dec 2014 13:52:00 -0500')
# datetime.datetime(2014, 12, 13, 13, 52, tzinfo=tzoffset(None, -18000))
Now, to print the timezone abbreviation EST requires that you convert the
timezone-aware datetime to the 'US/Eastern' timezone. This can be done using pytz.
This can not be done
automatically since there are other timezones, such as 'America/Bogota', which have the same utcoffset.
import pytz
eastern = pytz.timezone('US/Eastern')
observationTime = observationTime.astimezone(eastern)
print(observationTime.strftime('%b %d %Y %H:%M %p %Z'))
# Dec 13 2014 13:52 PM EST
print(observationTime.strftime('%b %d %Y %H:%M %z'))
# Dec 13 2014 13:52 -0500
bogota = pytz.timezone('America/Bogota')
observationTime = observationTime.astimezone(bogota)
print(observationTime.strftime('%b %d %Y %H:%M %p %Z'))
# Dec 13 2014 13:52 PM COT
print(observationTime.strftime('%b %d %Y %H:%M %z'))
# Dec 13 2014 13:52 -0500
(Note 13:52 is PM, not AM...)