Converting python time stamp to day of year - python

How can I convert a python timestamp into day of year:
Timestamp('2015-06-01 00:00:00')
I want a number where Jan 1 is 1, Jan 2 is 2... Dec 31 is 365 (for a non-leap year)

You might want to take a look at the function datetime.timetuple() which returns a time.struct_time object with your desired attribute. It has a named tuple interface, so you can access the values by index or attribute name.
import datetime
date = datetime.datetime.strptime("2015-06-01 00:00:00",
"%Y-%m-%d %H:%M:%S")
print date.timetuple().tm_yday
#=> 152

First, you can convert it to a datetime.datetime object like this:
>>> import datetime
>>> format = "%Y-%m-%d %H:%M:%S"
>>> s = "2015-06-01 00:00:00"
>>> dt = datetime.datetime.strptime(s, format)
Now you can use the methods on dt to get what you want,except that dt doesn't have the function you want directly, so you need to convert to a time tuple
>>> tt = dt.timetuple()
>>> tt.tm_yday
152

Related

Remove time in date format in Python

I using:
s = "20200113"
final = datetime.datetime.strptime(s, '%Y%m%d')
I need convert a number in date format (2020-01-13)
but when I print final:
2020-01-13 00:00:00
Tried datetime.date(s, '%Y%m%d') but It's returns a error:
an integer is required (got type str)
Is there any command to get only date without hour?
Once you have a datetime object just use strftime
import datetime
d = datetime.datetime.now() # Some datetime object.
print(d.strftime('%Y-%m-%d'))
which gives
2020-02-20
You can use strftime to convert back in the format you need :
import datetime
s = "20200113"
temp = datetime.datetime.strptime(s, '%Y%m%d')
# 2020-01-13 00:00:00
final = temp.strftime('%Y-%m-%d')
print(final)
# 2020-01-13
Use datetime.date(year, month, day). Slice your string and convert to integers to get the year, month and day. Now it is a datetime.date object, you can use it for other things. Here, however, we use .strftime to convert it back to text in your desired format.
s = "20200113"
year = int(s[:4]) # 2020
month = int(s[4:6]) # 1
day = int(s[6:8]) # 13
>>> datetime.date(year, month, day).strftime('%Y-%m-%d')
'2020-01-13'
You can also convert directly via strings.
>>> f'{s[:4]}-{s[4:6]}-{s[6:8]}'
'2020-01-13'
You can use .date() on datetime objects to 'remove' the time.
my_time_str = str(final.date())
will give you the wanted result

python json date object to python datetime

I have a JSON object with a date that returns
print row['ApplicationReceivedDateTime']
/Date(1454475600000)/
how do I process this using the pythons datetime module?
print type(row['ApplicationReceivedDateTime'])
returns <type 'unicode'>
print repr(row['ApplicationReceivedDateTime'])
returns u'/Date(1454475600000)/'
That looks like milliseconds. Try dividing by 1000.
import datetime as dt
>>> dt.datetime.fromtimestamp(1454475600000 / 1000)
datetime.datetime(2016, 2, 2, 21, 0)
If the date is in the string format per your question, extract the numeric portion using re.
date = '/Date(1454475600000)/'
>>> dt.datetime.fromtimestamp(int(re.findall(r"\d+", date)[0]) / 1000)
datetime.datetime(2016, 2, 2, 21, 0)
You probably want
datetime.datetime.strptime(string_date, "%Y-%m-%d %H:%M:%S.%f")
And the values of Year, Month, Day, Hour, Minute, Second and F, for that you can write a manual function for that like this
def generate_date_time_str(date_str):
"""Login to parse the date str"""
return date_str
the date_str will look link this
"%Y-%m-%d %H:%M:%S.%f"
There is no python module directly convert any random date str to DateTime object
You can use re to get the integer value and then use datetime.datetime.fromtimestamp to get the date value:
from datetime import datetime
import re
string_time = row['ApplicationReceivedDateTime']
parsed_time = int(re.search('\((\d+)\)', string_time)[1]) / 1e3 #1e3 == 1000
rcvd_date = datetime.fromtimestamp(parsed_time)
print(rcvd_date.strftime('%Y-%m-%d %H:%M:%S'))
Prints:
'2016-02-03 05:00:00'

Delta time string to datetime object

Given a string that looks like "Hours:5 Minutes:34 Seconds:28" or "Minutes:34 Seconds:28", is there any pythonic way to convert it to a datetime object? I do not want to use a regex if there's an easier way.
Yes, there is. You can do it like this:
import time
datetime_string = "Hours:5 Minutes:34 Seconds:28"
if "Hours" in datetime_string:
datetime_object = time.strptime(datetime_string, "Hours:%H Minutes:%M Seconds:%S")
elif "Minutes" in datetime_string:
datetime_object = time.strptime(datetime_string, "Minutes:%M Seconds:%S")
else:
datetime_object = time.strptime(datetime_string, "Seconds:%S")
Note: When You create datetime object, values that You do not provide will be filled with default values.So, in case datetime_string contains only seconds, hours and minutes will be set to 0.
You may use datetime.strptime() to convert string into datetime object as:
>>> from datetime import datetime
>>> date_object = datetime.strptime('Hours:5 Minutes:34 Seconds:28', 'Hours:%H Minutes:%M Seconds:%S')
>>> date_object
datetime.datetime(1900, 1, 1, 5, 34, 28)
# ^ ^ ^
# Hour Min Seconds
Since you do not have date in the string, it will keep the default date of 1 Jan 1990. I think what you need is datetime.time() which return time object with same hour, minute, second and microsecond as in you datetime object. (tzinfo is None). For example:
>>> date_object.time()
datetime.time(5, 34, 28)
# ^ ^ ^
# Hour Min Seconds
where date_object is of datetime type created earlier.

python datetime swapping day month

I have a date time object that looks like:
2015-31-12 00:34:00
where the second element (31) represents the day and the third element (12) represents the month. How do I swap day and month so that the date looks like:
2015-12-31 00:34:00
You'd parse the string into a datetime object then format it again back to a string:
from datetime import datetime
result = datetime.strptime(inputstring, '%Y-%d-%m %H:%M:%S').strftime('%Y-%m-%d %H:%M:%S')
Demo:
>>> from datetime import datetime
>>> inputstring = '2015-31-12 00:34:00'
>>> datetime.strptime(inputstring, '%Y-%d-%m %H:%M:%S').strftime('%Y-%m-%d %H:%M:%S')
'2015-12-31 00:34:00'
So the datetime.strptime() parses the string given a pattern, where you specify that the order is year-day-month, and datetime.strftime() formats it back to a string, with the day and month positions swapped.
Use .strftime('%Y-%m-%d %H:%M:%S').
For example:
from datetime import datetime
formatted_date = datetime.today().strftime('%Y-%m-%d %H:%M:%S')

Python - Time delta from string and now()

I have spent some time trying to figure out how to get a time delta between time values. The only issue is that one of the times was stored in a file. So I have one string which is in essence str(datetime.datetime.now()) and datetime.datetime.now().
Specifically, I am having issues getting a delta because one of the objects is a datetime object and the other is a string.
I think the answer is that I need to get the string back in a datetime object for the delta to work.
I have looked at some of the other Stack Overflow questions relating to this including the following:
Python - Date & Time Comparison using timestamps, timedelta
Comparing a time delta in python
Convert string into datetime.time object
Converting string into datetime
Example code is as follows:
f = open('date.txt', 'r+')
line = f.readline()
date = line[:26]
now = datetime.datetime.now()
then = time.strptime(date)
delta = now - then # This does not work
Can anyone tell me where I am going wrong?
For reference, the first 26 characters are acquired from the first line of the file because this is how I am storing time e.g.
f.write(str(datetime.datetime.now())
Which would write the following:
2014-01-05 13:09:42.348000
time.strptime returns a struct_time.
datetime.datetime.now() returns a datetime object.
The two can not be subtracted directly.
Instead of time.strptime you could use datetime.datetime.strptime, which returns a datetime object. Then you could subtract now and then.
For example,
import datetime as DT
now = DT.datetime.now()
then = DT.datetime.strptime('2014-1-2', '%Y-%m-%d')
delta = now - then
print(delta)
# 3 days, 8:17:14.428035
By the way, you need to supply a date format string to time.strptime or DT.datetime.strptime.
time.strptime(date)
should have raised a ValueError.
It looks like your date string is 26 characters long. That might mean you have a date string like 'Fri, 10 Jun 2011 11:04:17 '.
If that is true, you may want to parse it like this:
then = DT.datetime.strptime('Fri, 10 Jun 2011 11:04:17 '.strip(), "%a, %d %b %Y %H:%M:%S")
print(then)
# 2011-06-10 11:04:17
There is a table describing the available directives (like %Y, %m, etc.) here.
Try this:
import time
import datetime
d = datetime.datetime.now()
now = time.mktime(d.timetuple())
And then apply the delta
if you have the year,month,day of 'then' you may use:
year = 2013
month = 1
day = 1
now_date = datetime.datetime.now()
then_date = now_date.replace(year = year, month = month, day = day)
delta = now_date - then_date

Categories

Resources