I have a time which is 13:11:06 and i want to -GMT (i.e -0530). I can minus it by simply doing -5 by splitting the string taking the first digit (convert to int) and then minus it and then re-join. But then i get it in a format which is 8:11:06 which is not right as it should be 08:11:06, secondly its a lengthy process. Is there a easy way to get my time in -GMT format (08:11:06)
This is what i did to get -GMT time after getting the datetime
timesplithour = int(timesplit[1]) + -5
timesplitminute = timesplit[2]
timesplitseconds = timesplit[3]
print timesplithour
print timesplitminute
print timesplitseconds
print timesplithour + ":" + timesplitminute + ":" + timesplitseconds
You could use Python's datatime library to help you as follows:
import datetime
my_time = "13:11:06"
new_time = datetime.datetime.strptime("2016 " + my_time, "%Y %H:%M:%S") - datetime.timedelta(hours=5, minutes=30)
print new_time.strftime("%H:%M:%S")
This would print:
07:41:06
First it converts your string into a datetime object. It then creates a timedelta object allowing you to subtract 5 hours 30 minutes from the datetime object. Finally it uses strftime to format the resulting datetime into a string in the same format.
Use the datetime module:
from datetime import datetime, timedelta
dt = datetime.strptime('13:11:06', '%H:%M:%S')
time_gmt = (dt - timedelta(hours=5, minutes=30)).time()
print(time_gmt.hour)
print(time_gmt.minute)
print(time_gmt.second)
s = time_gmt.strftime('%H:%M:%S')
print(s)
Output
7
41
6
07:41:06
Note that this subtracts 5 hours and 30 minutes as initially mentioned in the question. If you really only want to subtract 5 hours, use timedelta(hours=5).
You can use datetimes timedelta.
print datetime.datetime.today()
>>> datetime.datetime(2016, 3, 3, 10, 45, 6, 270711)
print datetime.datetime.today() - datetime.timedelta(days=3)
>>> datetime.datetime(2016, 2, 29, 10, 45, 8, 559073)
This way you can subtract easily
Assuming the time is a datetime instance
import datetime as dt
t = datetime(2015,12,31,13,11,06)
#t.time() # gives time object. ie no date information
offset = dt.timedelta(hours=5,minutes=30) # or hours=5.5
t -= offset
t.strftime(("%H:%M:%S") # output as your desired string
#'18:41:06'
If the object is datetime and you don't care about DST, the simplest thing you can do is,
In [1]: from datetime import datetime
In [2]: curr = datetime.now()
In [3]: curr
Out[3]: datetime.datetime(2016, 3, 3, 9, 57, 31, 302231)
In [4]: curr.utcnow()
Out[4]: datetime.datetime(2016, 3, 3, 8, 57, 57, 286956)
Related
I have a date string and want to convert it to the date type:
I have tried to use datetime.datetime.strptime with the format that I want but it is returning the time with the conversion.
when = alldates[int(daypos[0])]
print when, type(when)
then = datetime.datetime.strptime(when, '%Y-%m-%d')
print then, type(then)
This is what the output returns:
2013-05-07 <type 'str'>
2013-05-07 00:00:00 <type 'datetime.datetime'>
I need to remove the time: 00:00:00.
print then.date()
What you want is a datetime.date object. What you have is a datetime.datetime object. You can either change the object when you print as per above, or do the following when creating the object:
then = datetime.datetime.strptime(when, '%Y-%m-%d').date()
If you need the result to be timezone-aware, you can use the replace() method of datetime objects. This preserves timezone, so you can do
>>> from django.utils import timezone
>>> now = timezone.now()
>>> now
datetime.datetime(2018, 8, 30, 14, 15, 43, 726252, tzinfo=<UTC>)
>>> now.replace(hour=0, minute=0, second=0, microsecond=0)
datetime.datetime(2018, 8, 30, 0, 0, tzinfo=<UTC>)
Note that this returns a new datetime object -- now remains unchanged.
>>> print then.date(), type(then.date())
2013-05-07 <type 'datetime.date'>
To convert a string into a date, the easiest way AFAIK is the dateutil module:
import dateutil.parser
datetime_object = dateutil.parser.parse("2013-05-07")
It can also handle time zones:
print(dateutil.parser.parse("2013-05-07"))
>>> datetime.datetime(2013, 5, 7, 1, 12, 12, tzinfo=tzutc())
If you have a datetime object, say:
import pytz
import datetime
now = datetime.datetime.now(pytz.UTC)
and you want chop off the time part, then I think it is easier to construct a new object instead of "substracting the time part". It is shorter and more bullet proof:
date_part datetime.datetime(now.year, now.month, now.day, tzinfo=now.tzinfo)
It also keeps the time zone information, it is easier to read and understand than a timedelta substraction, and you also have the option to give a different time zone in the same step (which makes sense, since you will have zero time part anyway).
For me, I needed to KEEP a timetime object because I was using UTC and it's a bit of a pain. So, this is what I ended up doing:
date = datetime.datetime.utcnow()
start_of_day = date - datetime.timedelta(
hours=date.hour,
minutes=date.minute,
seconds=date.second,
microseconds=date.microsecond
)
end_of_day = start_of_day + datetime.timedelta(
hours=23,
minutes=59,
seconds=59
)
Example output:
>>> date
datetime.datetime(2016, 10, 14, 17, 21, 5, 511600)
>>> start_of_day
datetime.datetime(2016, 10, 14, 0, 0)
>>> end_of_day
datetime.datetime(2016, 10, 14, 23, 59, 59)
If you specifically want a datetime and not a date but want the time zero'd out you could combine date with datetime.min.time()
Example:
datetime.datetime.combine(datetime.datetime.today().date(),
datetime.datetime.min.time())
You can use simply pd.to_datetime(then) and pandas will convert the date elements into ISO date format- [YYYY-MM-DD].
You can pass this as map/apply to use it in a dataframe/series too.
You can usee the following code:
week_start = str(datetime.today() - timedelta(days=datetime.today().weekday() % 7)).split(' ')[0]
I want to subtract 2 times and convert that into a time array.
I consulted this How to calculate the time interval between two time strings. Stating this following code
from datetime import datetime as dt
import time
print("Time Subtraction")
FMT = '%Y-%m-%d %H:%M:%S'
time_tuple = (2018, 1, 13, 13, 51, 18, 2, 317, 0)
time2_tuple = (2018, 1, 15, 13, 50, 18, 2, 317, 0)
s1 = time.strftime(FMT, time_tuple)
s2 = time.strftime(FMT, time2_tuple)
tdelta = dt.strptime(s2, FMT) - dt.strptime(s1, FMT)
print(tdelta)
The result is:
Time Subtraction
1 day, 23:59:00
But I want to get a tuple/print that will look like this
tuple = (0,0,1,23,59,0,2,317,0)
I usually use time not datetime so I am not sure what to do. Any ideas?
tdelta is a datetime.timedelta object, therefore you are printing the string representation of that object. You can get the days, hours, minutes, etc by performing simple arithmetic (since they are stored as fractions-of-days) on the attributes:
def days_hours_minutes(delta):
return delta.days, delta.seconds//3600, (delta.seconds//60)%60
You can add as many of these attributes to the tuple as you'd like.
The output of
/sbin/hwclock --show --utc
looks like
2017-06-01 16:04:47.029482+1:00
How to parse this string into a datetime object in Python?
You can use the third party library python-dateutil (pip install python-dateutil):
>>> import dateutil.parser
>>> dateutil.parser.parse('2017-06-01 16:04:47.029482+1:00')
datetime.datetime(2017, 6, 1, 16, 4, 47, 29482, tzinfo=tzoffset(None, 3600))
If you don't want to use a third party library:
import datetime
import re
def parse_iso_timestamp(clock_string):
# Handle offset < 10
clock_string = re.sub(r'\+(\d):', r'+0\1', clock_string)
# Handle offset > 10
clock_string = re.sub(r'\+(\d\d):', r'+\1', clock_string)
# Parse
dt = datetime.datetime.strptime(clock_string, '%Y-%m-%d %H:%M:%S.%f%z')
return dt
print(parse_iso_timestamp('2017-06-01 16:04:47.029482+1:00').__repr__())
print(parse_iso_timestamp('2017-06-01 16:04:47.029482+10:00').__repr__())
Which outputs:
datetime.datetime(2017, 6, 1, 16, 4, 47, 29482, tzinfo=datetime.timezone(datetime.timedelta(0, 3600)))
datetime.datetime(2017, 6, 1, 16, 4, 47, 29482, tzinfo=datetime.timezone(datetime.timedelta(0, 36000)))
using just datetime:
import datetime
s = "2017-06-01 16:04:47.029482+1:00"
try:
stamp, zone = s.rsplit('+', 1)
sign = '+'
except ValueError:
stamp, zone = s.rsplit('-', 1)
sign = '-'
zone = int(zone.replace(':', ''))
new_s = '%s%s%04d' % (stamp, sign, zone)
print(new_s)
dt = datetime.datetime.strptime(new_s, "%Y-%m-%d %H:%M:%S.%f%z")
print(dt.__repr__())
You can parse a string into datetime object using datetime.strptime(). It takes the date string and format as input and return datetime object method.
split by space fist value is date like 2017-06-01
d =date.split(" ")[0]
split by dot to get time
t = data.split(" ")[1].split(".")[0]
A function returns date and time in unicode format.
u'2014-03-06T04:38:51Z'
I wish to convert this to date and time format and subtract it with current datetime to get the number of days in between.
Thanks in advance
Check string is unicode
>>> import types
>>> type(u'2014-03-06T04:38:51Z') is types.UnicodeType
True
Converting strings to datetime:
>>> import datetime
>>> datetime.datetime.strptime(u'2014-03-06T04:38:51Z', '%Y-%m-%dT%H:%M:%SZ')
datetime.datetime(2014, 3, 6, 4, 38, 51)
Subtract from today to
>>> import datetime
>>> today = datetime.datetime.today()
>>> yourdate = datetime.datetime.strptime(u'2014-03-06T04:38:51Z', '%Y-%m-%dT%H:%M:%SZ')
>>> difference = today - yourdate
print str(difference)
First you have to convert your string to a datetime.datetime object.
import datetime
then = datetime.datetime.strptime(u'2014-03-06T04:38:51Z', "%Y-%m-%dT%H:%M:%SZ")
then represents itself as datetime.datetime(2014, 3, 6, 4, 38, 51), which looks about right. Then you have to get today's date as a datetime.datetime.
now = datetime.datetime.now()
Finally subtract it from your date (or vice versa - the question didn't make it clear).delta is a datetime.timedelta object that stores increments in days, seconds and microseconds. The latter two are always positive, the first can be negative.
for delta in (now-then, then-now):
print(delta, "::", delta.days, delta.seconds, delta.microseconds)
This prints out:
-1 day, 20:18:14.250142 :: -1 73094 250142
3:41:45.749858 :: 0 13305 749858
Best try it with a few examples to convince yourself it's correct.
I have a utc timestamp in the IS8601 format and am trying to convert it to unix time. This is my console session:
In [9]: mydate
Out[9]: '2009-07-17T01:21:00.000Z'
In [10]: parseddate = iso8601.parse_date(mydate)
In [14]: ti = time.mktime(parseddate.timetuple())
In [25]: datetime.datetime.utcfromtimestamp(ti)
Out[25]: datetime.datetime(2009, 7, 17, 7, 21)
In [26]: datetime.datetime.fromtimestamp(ti)
Out[26]: datetime.datetime(2009, 7, 17, 2, 21)
In [27]: ti
Out[27]: 1247815260.0
In [28]: parseddate
Out[28]: datetime.datetime(2009, 7, 17, 1, 21, tzinfo=<iso8601.iso8601.Utc object at 0x01D74C70>)
As you can see, I can't get the correct time back. The hour is ahead by one if i use fromtimestamp(), and it's ahead by six hours if i use utcfromtimestamp()
Any advice?
Thanks!
You can create an struct_time in UTC with datetime.utctimetuple() and then convert this to a unix timestamp with calendar.timegm():
calendar.timegm(parseddate.utctimetuple())
This also takes care of any daylight savings time offset, because utctimetuple() normalizes this.
I am just guessing, but one hour difference can be not because of time zones, but because of daylight savings on/off.
naive_utc_dt = parseddate.replace(tzinfo=None)
timestamp = (naive_utc_dt - datetime(1970, 1, 1)).total_seconds()
# -> 1247793660.0
See more details in another answer to similar question.
And back:
utc_dt = datetime.utcfromtimestamp(timestamp)
# -> datetime.datetime(2009, 7, 17, 1, 21)
import time
import datetime
import calendar
def date_time_to_utc_epoch(dt_utc): #convert from utc date time object (yyyy-mm-dd hh:mm:ss) to UTC epoch
frmt="%Y-%m-%d %H:%M:%S"
dtst=dt_utc.strftime(frmt) #convert datetime object to string
time_struct = time.strptime(dtst, frmt) #convert time (yyyy-mm-dd hh:mm:ss) to time tuple
epoch_utc=calendar.timegm(time_struct) #convert time to to epoch
return epoch_utc
#----test function --------
now_datetime_utc = int(date_time_to_utc_epoch(datetime.datetime.utcnow()))
now_time_utc = int(time.time())
print (now_datetime_utc)
print (now_time_utc)
if now_datetime_utc == now_time_utc :
print ("Passed")
else :
print("Failed")