I'm pulling a timestamp that looks like this - 2014-02-03T19:24:07Z
I'm trying to calculate the number of days since January 1.
I was able to convert it to datetime using
yourdate = dateutil.parser.parse(timestamp)
But now I'm trying to parse it and grab individual elements, such as the month & day.
Is there a way to convert it to strptime so I can select each element?
Just access the month, day using year, month, day attributes..
>>> import dateutil.parser
>>> yourdate = dateutil.parser.parse('2014-02-03T19:24:07Z')
>>> yourdate.year
2014
>>> yourdate.month
2
>>> yourdate.day
3
Just to be a little more complete:
>>> from dateutil.parser import parse
>>> from datetime import datetime
>>> import pytz
>>> d = parse('2014-02-03T19:24:07Z')
>>> other = datetime(year=2014, month=1, day=1, tzinfo=pytz.utc)
>>> (d-other).days
33
You have to make sure the other datetime is timezone aware if you're creating it with datetime as opposed to the datetime you're parsing with dateutil.
There's no need for converting. The resulting datetime.datetime object has all necessary properties which you can access directly. For example:
>>> import dateutil.parser
>>> timestamp="2014-02-03T19:24:07Z"
>>> yourdate = dateutil.parser.parse(timestamp)
>>> yourdate.day
3
>>> yourdate.month
2
See: https://docs.python.org/2/library/datetime.html#datetime-objects
if you want to calculate:
import dateutil.parser
yourdate = dateutil.parser.parse('2014-02-03T19:24:07Z')
startdate = dateutil.parser.parse('2014-01-01T00:00:00Z')
print (yourdate - startdate)
Another way to solve without the dateutil module:
import datetime
# start date for comparision
start = datetime.date(2014, 1, 1)
# timestamp as string
datefmt = "%Y-%m-%dT%H:%M:%SZ"
current = "2014-02-03T19:24:07Z"
# convert timestamp string to date, dropping time
end = datetime.datetime.strptime(current, datefmt).date()
# compare dates and get number of days from timedelta object
days = (end - start).days
This assumes you don't care about time (including timezones).
Related
As an input to an API request I need to get yesterday's date as a string in the format YYYY-MM-DD. I have a working version which is:
yesterday = datetime.date.fromordinal(datetime.date.today().toordinal()-1)
report_date = str(yesterday.year) + \
('-' if len(str(yesterday.month)) == 2 else '-0') + str(yesterday.month) + \
('-' if len(str(yesterday.day)) == 2 else '-0') + str(yesterday.day)
There must be a more elegant way to do this, interested for educational purposes as much as anything else!
You Just need to subtract one day from today's date. In Python datetime.timedelta object lets you create specific spans of time as a timedelta object.
datetime.timedelta(1) gives you the duration of "one day" and is subtractable from a datetime object. After you subtracted the objects you can use datetime.strftime in order to convert the result --which is a date object-- to string format based on your format of choice:
>>> from datetime import datetime, timedelta
>>> yesterday = datetime.now() - timedelta(1)
>>> type(yesterday)
>>> datetime.datetime
>>> datetime.strftime(yesterday, '%Y-%m-%d')
'2015-05-26'
Note that instead of calling the datetime.strftime function, you can also directly use strftime method of datetime objects:
>>> (datetime.now() - timedelta(1)).strftime('%Y-%m-%d')
'2015-05-26'
As a function:
from datetime import datetime, timedelta
def yesterday(frmt='%Y-%m-%d', string=True):
yesterday = datetime.now() - timedelta(1)
if string:
return yesterday.strftime(frmt)
return yesterday
example:
In [10]: yesterday()
Out[10]: '2022-05-13'
In [11]: yesterday(string=False)
Out[11]: datetime.datetime(2022, 5, 13, 12, 34, 31, 701270)
An alternative answer that uses today() method to calculate current date and then subtracts one using timedelta(). Rest of the steps remain the same.
https://docs.python.org/3.7/library/datetime.html#timedelta-objects
from datetime import date, timedelta
today = date.today()
yesterday = today - timedelta(days = 1)
print(today)
print(yesterday)
Output:
2019-06-14
2019-06-13
>>> import datetime
>>> datetime.date.fromordinal(datetime.date.today().toordinal()-1).strftime("%F")
'2015-05-26'
Calling .isoformat() on a date object will give you YYYY-MM-DD
from datetime import date, timedelta
(date.today() - timedelta(1)).isoformat()
I'm trying to use only import datetime based on this answer.
import datetime
oneday = datetime.timedelta(days=1)
yesterday = datetime.date.today() - oneday
I have a date timestamp like "2013-12-20 23:40:33". Now, my requirement is to re-format this date in reverse order like :
<seconds><minutes><hr><day><month><year>
in python. Please suggest
Load the string into a datetime object with strptime and format to string with strftime:
>>> from datetime import datetime
>>> datetime.strptime(s, '%Y-%m-%d %H:%M:%S').strftime('%S:%M:%H %d-%m-%Y')
'33:40:23 20-12-2013'
>>> import datetime
>>> datetime.datetime.strptime('2013-12-20 23:40:33', '%Y-%m-%d %H:%M:%S').strftime('%S:%M:%H %d-%m-%Y')
'33:40:23 20-12-2013'
If you don't need to validate the time string:
>>> import re
>>> '<%s>' % '><'.join(re.findall(r'\d+', "2013-12-20 23:40:33")[::-1])
'<33><40><23><20><12><2013>'
It is 6 times faster than the corresponding datetime solution:
>>> from datetime import datetime
>>> datetime.strptime("2013-12-20 23:40:33", '%Y-%m-%d %H:%M:%S').strftime('<%S><%M><%H><%d><%m><%Y>')
'<33><40><23><20><12><2013>'
Or 5 times faster than time solution:
>>> import time
>>> time.strftime('<%S><%M><%H><%d><%m><%Y>', time.strptime("2013-12-20 23:40:33", '%Y-%m-%d %H:%M:%S'))
'<33><40><23><20><12><2013>'
d = "2013-12-20 23:40:33"
date = d[17]+d[18]+":"+d[14]+d[15]+":"+d[11]+d[12]+" "+d[8]+d[9]+"-"+d[5]+d[6]+"-"+d[0]+d[1]+d[2]+d[3]
print(d)
print(date)
I need to convert time stored in a variable in the format using Python <=2.7
07/20-10:38:04.360700
to epoch time (since Midnight, Jan 1st, 1970) like this
1405852684.360700
Is it best to import the time module, or just split and use some math calculations?
If the string date is with respect to UTC, then:
In [31]: import datetime as DT
In [32]: text = '07/20-10:38:04.360700'
In [33]: date = DT.datetime.strptime('2014/'+text, '%Y/%m/%d-%H:%M:%S.%f')
In [34]: (date - DT.datetime(1970,1,1)).total_seconds()
Out[34]: 1405852684.3607
If the string date refers to a date with respect to some other timezone, then you could use pytz to make the datetime timezone-aware before doing the calculation. For example,
import pytz
import datetime as DT
text = '07/20-10:38:04.360700'
tz = pytz.timezone('US/Eastern')
date = DT.datetime.strptime('2014/'+text, '%Y/%m/%d-%H:%M:%S.%f')
# interpret the date as coming from US/Eastern
date_tz = tz.localize(date)
epoch = DT.datetime(1970,1,1, tzinfo=pytz.utc)
timestamp = (date_tz - epoch).total_seconds()
print(repr(timestamp))
# 1405867084.3607
You can use python's timetuple() function (and a little math)
>>> import datetime
>>> import time
>>> v = datetime.datetime(2014, 7, 20, 10, 38, 4, 360700)
>>> time.mktime(v.timetuple())
1405870684.0
Now we need your microseconds:
>>> time.mktime(v.timetuple())+(v.microsecond/1000000.)
1405870684.3607
You don't specify the year so here I assume that it is the current year. The following assumes that all times are UTC, i.e. not local time.
from datetime import datetime
time_string = '07/20-10:38:04.360700'
dt = datetime.strptime(time_string, '%m/%d-%H:%M:%S.%f')
dt = dt.replace(year=datetime.today().year)
>>> (dt - datetime.utcfromtimestamp(0)).total_seconds()
1405852684.3607
I have a program (sar command line utility) which outputs it's lines with time column. I parse this file with my python script and I would like to convert sar's 02:31:33 PM into epochs e.g. 1377181906 (current year, month and day with hours, minutes and seconds from abovementioned string). How can this done in a less cumbersome way? I tried to do this by myself, but stuck with time/datetime and herd of their methods.
Here's one way to do it:
read the string into datetime using strptime
set year, month, day of the datetime object to current date's year, month and day via replace
convert datetime into unix timestamp via calendar.timegm
>>> from datetime import datetime
>>> import calendar
>>> dt = datetime.strptime("02:31:33 PM", "%I:%M:%S %p")
>>> dt_now = datetime.now()
>>> dt = dt.replace(year=dt_now.year, month=dt_now.month, day=dt_now.day)
>>> calendar.timegm(dt.utctimetuple())
1377138693
Note that in python >= 3.3, you can get the timestamp from a datetime by calling dt.timestamp().
Also see:
Python Create unix timestamp five minutes in the future
An another way to have epoch time is to use mktime from time module and pass time tuple of date, so you can do this:
>>> from datetime import datetime
>>> from time import mktime
>>> dt = datetime.strptime("02:31:33 PM", "%H:%M:%S %p")
>>> dt_now = datetime.now()
>>> dt = dt.replace(year=dt_now.year, month=dt_now.month, day=dt_now.day)
>>> int(mktime(dt.timetuple()))
1377131493
In Sweden we sometimes use a strange date format, for example New Year is the 31/12. If I have this format as a string ,which can be any date between 1/1 and 31/12, and if we assume that it is this year, how do I get into a standard date format using Python (format as 2012-01-01 and 2012-12-31) that can be sore in be stored as a date in a mySQL database.
Simply split the two values, map them to integers and update a datetime.date() instance:
import datetime
day, month = map(int, yourvalue.split('/'))
adate = datetime.date.today().replace(month=month, day=day)
By using datetime.date.today() we get the current year.
Demo:
>>> import datetime
>>> somevalue = '31/12'
>>> day, month = map(int, somevalue.split('/'))
>>> datetime.date.today().replace(month=month, day=day)
datetime.date(2012, 12, 31)
>>> someothervalue = '1/1'
>>> day, month = map(int, someothervalue.split('/'))
>>> datetime.date.today().replace(month=month, day=day)
datetime.date(2012, 1, 1)
Alternatively, you could use the datetime.strptime() method to parse these dates, but you'll have to manually correct the year afterwards (it'll use 1900 as the default if no year is being parsed):
adate = datetime.datetime.strptime(yourvalue, '%d/%m').date()
adate = adate.replace(year=datetime.date.today().year)
There is nothing strange about this format :)
You can use the datetime module:
import datetime
d = datetime.datetime.strptime('31/12', '%d/%m').date().replace(year=2012)
print d
>> datetime.date(2012, 12, 31)