Handling of timezones in strptime in Python [duplicate] - python

This question already has answers here:
How to parse dates with -0400 timezone string in Python?
(6 answers)
Convert string "Jun 1 2005 1:33PM" into datetime
(26 answers)
Closed 6 years ago.
I have two string like these:
"Sun 10 May 2015 13:54:36 -0700"
"Sun 10 May 2015 13:54:36 +0000"
(The last part is time zone -0700 means 7 hours less than GMT)
My intention is turn it to a unix timestamp to find their absolute difference easily.
My Question is is there a built-in method for turning these formated texts to Unix timestamp? Or Is there a one that computes difference of two such strings directly??
Edit:
This Question differs from This one since that problem doesn't include time zones and not any of answers to that question mentioned anything about time zone.

This should work on Python 3 & above but not known to work on all platforms on Python 2.
date_str = "Sun 10 May 2015 13:54:36 -0700"
pattern = '%a %d %B %Y %H:%M:%S %z'
dt = int(time.mktime(time.strptime(date_str ,pattern )))
print(dt)
For, Python 2.7+, (without %z)
import datetime
date_str = "Sun 10 May 2015 13:54:36 -0700"
dt_str = date_str[:-5].strip()
dt_zone = int(date_str[-5:])/100
pattern = '%a %d %B %Y %H:%M:%S'
dtobj = datetime.datetime.strptime(dt_str ,pattern)
dt = dtobj + datetime.timedelta(hours=dt_zone)
print( dt.strftime('%s') )

This code answer to your question:
from datetime import timedelta, datetime, tzinfo
date1="Sun 10 May 2015 13:54:36 -0700"
date2=date1[4:-6]
zone = int(date1[-5:])/100
d=datetime.strptime(date2, "%d %B %Y %H:%M:%S")
class TZ(tzinfo):
def utcoffset(self, dt): return timedelta(hours=zone)
d=datetime(d.year, d.month, d.day,d.hour,d.minute,d.second, tzinfo=TZ()).isoformat(' ')
print d

Related

Format email Date into "%Y-%m-%d %H:%M:%S" [duplicate]

This question already has answers here:
Convert timestamps with offset to datetime obj using strptime
(4 answers)
ISO to datetime object: 'z' is a bad directive [duplicate]
(2 answers)
Closed 3 years ago.
I'm trying to format the date of an email using python2.7. The value of date is like
Date: "Tue, 9 Apr 2019 11:49:26 -0400"
Here's the code:
"date": datetime.strptime(d_items['Date'], '%a,%d %b %Y %H:%M:%S %z').strftime('%Y-%m-%d %H:%M:%S')
While stripping the timezone and formatting I'm getting the below error using datetime.datetime function.
'z' is a bad directive in format '%a,%d %b %Y %H:%M:%S %z'
Is there any other way to get the format like below:
2019-04-09 11:49:26

Days between dates [duplicate]

This question already has answers here:
How to calculate number of days between two given dates
(15 answers)
How do I parse an HTTP date-string in Python?
(4 answers)
Closed 5 years ago.
I need count days to password change in linux.
I know how to do this in python e.g:
>>> import datetime
>>> start = datetime.date(2016,1,1)
>>> end = datetime.date(2016,2,28)
>>> end-start
But my date format is:
Oct 03, 2017
How I can calculate days to a date?
You can do this using strftime().
It is actually really simple:
from datetime import datetime
d1 = datetime.strptime("Jan 01, 2016", '%b %d, %Y')
d2 = datetime.strptime("Feb 28, 2016", '%b %d, %Y')
print "Delta (in days):", (d2-d1).days
And you'll get 58 as a result.

How to parse time retrieved from Facebook Graph into 12 hour format?

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

How to parse the date "Thu, 1 Oct 2015 16:05:43 +0200" in python? [duplicate]

This question already has answers here:
Convert timestamps with offset to datetime obj using strptime
(4 answers)
How to remove unconverted data from a Python datetime object
(5 answers)
Closed 7 years ago.
In python I am trying to parse the date string
Thu, 1 Oct 2015 16:05:43 +0200
to a struct_time trying
x = time.strptime(date_string, "%a, %d %b %Y %H:%M:%S +0000")
which yields a ValueError.
How to avoid the "+0200" (which I am not interested in)? Just remove the last 6 characters? Or is there a 'better' solution?
Just remove the last chunk; you can do that by slicing (removing the last 6 characters, yes), or by partitioning (splitting off the last section):
x = time.strptime(date_string.rpartition(' ')[0], "%a, %d %b %Y %H:%M:%S")
Partitioning should continue to work if the last chunk is not 6 characters (say, because you have dates with the timezone expressed as a 3-letter code).

Python Date / Time Regular Expression

I am pretty new to regular expressions and it's pretty alien to me. I am parsing an XML feed which produces a date time as follows:
Wed, 23 July 2014 19:25:52 GMT
But I want to split these up so there are as follows:
date = 23/07/2014
time = 19/25/52
Where would I start? I have looked at a couple of other questions on SO and all of them deviate a bit from what I am trying to achieve.
Use datetime.strptime to parse the date from string and then format it using the strftime method of datetime objects:
>>> from datetime import datetime
>>> dt = datetime.strptime("Wed, 23 July 2014 19:25:52 GMT", "%a, %d %B %Y %H:%M:%S %Z")
>>> dt.strftime('%d/%m/%Y')
'23/07/2014'
>>> dt.strftime('%H/%M/%S')
'19/25/52'
But if you're okay with the ISO format you can call date and time methods:
>>> str(dt.date())
'2014-07-23'
>>> str(dt.time())
'19:25:52'

Categories