Python module for date manipulation - python

Is there a python module specifically for date manipulation. Something equivalent to the lubridate package in R.

Python have a built-in module for handling datetime..You can try that..!!
But if want something extended (like want to build a generic datetime parser), go for python-dateutil
from dateutil.parser import parse
datetimeObj = parse(strDate)
# str date is a date string

Actually, Python's standard datetime module is pretty basic. If you want more extensive and flexible date handling, you can try dateutil or mxDateTime.

The python module arrow seems to be an equivalent of the R lubridate package:
import arrow
In [9]: arrow.get('Julie was born in May 1990', 'MMM YYYY')
Out[9]: <Arrow [1990-05-01T00:00:00+00:00]>

Try to use pytz
Documentation
http://pytz.sourceforge.net/

Related

converting between timezones (format same instance in time) in python 3

I have a list of timestamps which look like so:
time_list=['2016-10-01T00:00:00+01:00','2016-10-01T23:00:00+00:00','2016-10-01T22:00:00+02:00',..]
I would like to apply a magic function to this list which gets them all in +00:00 timezone - this should result in (all timestamps should correctly adjusted to the +00:00 format):
ret_list=['2016-10-01T23:00:00+00:00','2016-10-01T23:00:00+00:00','2016-10-01T23:00:00+00:00',..]
You have to convert your isoformat strings to datetime objects first, change timezones to UTC and then stringify back.
If you are on python 3.7, according to this, you can use fromisoformat method of datetime, but if you don't, like me, I think the best option involves the use of dateutil module (you have to install it) and pytz:
import datetime as dt
from dateutil import parser
import pytz
time_list = ['2016-10-01T00:00:00+01:00','2016-10-01T23:00:00+00:00','2016-10-01T22:00:00+02:00']
utc_time_list = [parser.parse(x).astimezone(pytz.utc).isoformat() for x in time_list]
print(utc_time_list)
['2016-09-30T23:00:00+00:00', '2016-10-01T23:00:00+00:00', '2016-10-01T20:00:00+00:00']

python convert human to timestamp

My date is in following format:
19/Jun/2014:00:03:09
How to I convert it to epoch timestamp in python?
Note: I searched on date format in python, but could not find any format that matches above.
Thanks.
Use strptime and then mktime.
import time
tt = time.strptime("19/Jun/2014:00:03:09","%d/%b/%Y:%H:%M:%S")
print time.mktime(tt)
import datetime
datetime.datetime.strptime(s, '%d/%b/%Y:%H:%M:%S')
reference
use dateutil it will parse just about anything
$ easy_install python-dateutil
>>> import dateutil.parser as parser
>>> some_date_string = "19/Jun/2014:00:03:09"
>>> parser.parse(some_date_string)
[edit] oops nevermind ... apparently it cant parse this ...

Convert datetime to local python

I have been reading quite some time answers and couldn't really drive into results.
I have the following code:
>>>from datetime import datetime
>>>a = '2013-08-23T23:37:38+0000'
>>>dt = datetime.strptime(a,'%Y-%m-%dT%H:%M:%S+0000')
>>>print dt.date()
2013-08-23
>>>print dt.time()
23:37:38
What is the simplest way to output this result (assuming of course that a is unknown) given that we live in Central Europe. So it should be "daylight saving-proof" as well.
In winter:
2013-08-24
00:37:38
In summer:
2013-08-24
01:37:38
If it only needs default libraries it would be great.
Some more info
I dived into the libraries after my question. My above 3rd line should be better be:
dt = datetime.strptime(a,'%Y-%m-%dT%H:%M:%S%z'). However a bug came out in 2.7.5 python (OS X if it matters) and had some trouble finding the %z. If you have trouble change version, if not ignore this. Of course the strptime() is just simpler level of dateutil.parser mentioned in the two answers so it can better be used instead of my code above.
you can use the useful dateutil package and the pytz one for exemple convert to paris timezone
from dateutil import parser
import pytz
FR = pytz.timezone('Europe/Paris') # there is the summer offset changing in this zone
date = parser.parse("2013-08-23T23:37:38+0000")
datefr = date.astimezone(FR)
Here's an example using pytz and dateutil:
from dateutil import parser
import pytz
date = parser.parse('2013-08-23T23:37:38+0000')
CET = pytz.timezone('CET')
date = date.astimezone(CET)
print date.date() # prints 2013-08-24
print date.time() # prints 01:37:38

How to convert Dates into Specified Format using python?

I have a list of dates as below:
list_dates = ['2013-05-01', '15th Oct 2013', '01-05-13', '2013/FEB/05',. . .]
What I want is:
list_dates = ['2013-05-01', '2013-10-15', '2013-05-01', '2013-02-05', . . .]
Is there ANY way, or package/module to accomplish this task?
You can try using the third-party library dateutil's parser, which is usually very good at determining the proper way to parse a date (at least way better than I'll ever be :) ). The result of parser.parse is a datetime object, on which you can call strftime with your desired format:
In [1]: from dateutil import parser
In [2]: list_dates = ['2013-05-01', '15th Oct 2013', '01-05-13', '2013/FEB/05']
In [3]: [parser.parse(date).strftime('%Y-%m-%d') for date in list_dates]
Out[3]: ['2013-05-01', '2013-10-15', '2013-01-05', '2013-02-05']
You can use datetime and time modules for this.
http://docs.python.org/2/library/datetime.html
http://docs.python.org/2/library/time.html
Try datetime.datetime, it provide strptime and strftime method to do this task.

Convert python datetime to epoch with strftime

I have a time in UTC from which I want the number of seconds since epoch.
I am using strftime to convert it to the number of seconds. Taking 1st April 2012 as an example.
>>>datetime.datetime(2012,04,01,0,0).strftime('%s')
'1333234800'
1st of April 2012 UTC from epoch is 1333238400 but this above returns 1333234800 which is different by 1 hour.
So it looks like that strftime is taking my system time into account and applies a timezone shift somewhere. I thought datetime was purely naive?
How can I get around that? If possible avoiding to import other libraries unless standard. (I have portability concerns).
If you want to convert a python datetime to seconds since epoch you could do it explicitly:
>>> (datetime.datetime(2012,4,1,0,0) - datetime.datetime(1970,1,1)).total_seconds()
1333238400.0
In Python 3.3+ you can use timestamp() instead:
>>> datetime.datetime(2012,4,1,0,0).timestamp()
1333234800.0
Why you should not use datetime.strftime('%s')
Python doesn't actually support %s as an argument to strftime (if you check at http://docs.python.org/library/datetime.html#strftime-and-strptime-behavior it's not in the list), the only reason it's working is because Python is passing the information to your system's strftime, which uses your local timezone.
>>> datetime.datetime(2012,04,01,0,0).strftime('%s')
'1333234800'
I had serious issues with Timezones and such. The way Python handles all that happen to be pretty confusing (to me). Things seem to be working fine using the calendar module (see links 1, 2, 3 and 4).
>>> import datetime
>>> import calendar
>>> aprilFirst=datetime.datetime(2012, 04, 01, 0, 0)
>>> calendar.timegm(aprilFirst.timetuple())
1333238400
import time
from datetime import datetime
now = datetime.now()
time.mktime(now.timetuple())
import time
from datetime import datetime
now = datetime.now()
# same as above except keeps microseconds
time.mktime(now.timetuple()) + now.microsecond * 1e-6
(Sorry, it wouldn't let me comment on existing answer)
if you just need a timestamp in unix /epoch time, this one line works:
created_timestamp = int((datetime.datetime.now() - datetime.datetime(1970,1,1)).total_seconds())
>>> created_timestamp
1522942073L
and depends only on datetime
works in python2 and python3
For an explicit timezone-independent solution, use the pytz library.
import datetime
import pytz
pytz.utc.localize(datetime.datetime(2012,4,1,0,0), is_dst=False).timestamp()
Output (float): 1333238400.0
This works in Python 2 and 3:
>>> import time
>>> import calendar
>>> calendar.timegm(time.gmtime())
1504917998
Just following the official docs...
https://docs.python.org/2/library/time.html#module-time
In Python 3.7
Return a datetime corresponding to a date_string in one of the formats
emitted by date.isoformat() and datetime.isoformat(). Specifically,
this function supports strings in the format(s)
YYYY-MM-DD[*HH[:MM[:SS[.fff[fff]]]][+HH:MM[:SS[.ffffff]]]], where *
can match any single character.
https://docs.python.org/3/library/datetime.html#datetime.datetime.fromisoformat

Categories

Resources