If date is provided as as 01st Jan, 2nd Jan, it should provide me an output in UTC along with current year and time as well.
Output : 2017-01-02T06:40:00Z
You cannot only use datetime module since the ordinals are not handled.
But you can use a regular expression to reformat your input, and then strptime to convert it to a datetime that you can convert back to string using strftime:
import re
import datetime
str_date = "2nd Jan"
now = datetime.datetime.utcnow()
PATTERN = re.compile(r"^0*(?P<day>[1-9]\d*)[^ ]* (?P<month>\w+)$")
reformatted = PATTERN.sub(r"\g<day> \g<month> %s", str_date) % now.strftime("%Y %H:%M:%S")
date = datetime.datetime.strptime(reformatted, "%d %b %Y %H:%M:%S")
print date.strftime("%Y-%m-%dT%H:%M:%SZ")
will output : 2017-01-02T09:03:54Z
Related
I'm trying to do some time math, but I'm not sure how I could do this. I'd like to subtract a specific date & time I have in a string (e.g.: 15:54:00 2017-5-20) from current GMT time (e.g: 20:06:27 2017-12-22).
Any thoughts on how I could do this?
# import data into Python
with open(output_file2) as f:
reader = csv.reader(f, delimiter="\t")
d = list(reader)
# here, objects [0][4] and [0][5] would be, for instance: 15:54:00 and 2017-5-20
# , respectively
# UTC Time
os.system("date -u \"+%H:%M:%S %Y-%m-%d\" | gawk '{print \" UTC Date & Time: \", $1, \"\", $2}'")
# eg.: 20:06:27 2017-12-22
Any thoughts would be great! Thanks =)
Update: I've tried so far:
UTC_time = datetime.datetime.utcnow().strftime("%H:%M:%S %Y-%m-%d")
print ' UTC Date & Time: ', UTC_time
time1 = d[0][4]
date1 = d[0][5]
mytime = time1, date1
time_difference = datetime.datetime.utcnow() - mytime
print "HELLO", time_difference
but I keep getting an error:
TypeError: unsupported operand type(s) for -: 'datetime.datetime' and 'tuple'
Not sure what I am doing wrong...
Your mytime variable is not a datetime.datetime object and cannot be used to operate against one. Instead of mytime = time1, date1 you are looking for something more along the lines of
my_date_str = "{} {}".format(time1, date1)
mytime = datetime.datetime.strptime(my_date_str, "%H:%M:%S %Y-%m-%d")
Do realize that in spite of using utcnow() the resulting datetime.datetime object is NOT timezone aware, and neither is mytime. So any math between the two is pure clock math, no timezones taken into account.
If you require timezone support, look into pytz or Pendulum or perhaps find another if they don't suit you.
I am trying to convert local date time to UTC format but I am unable to convert Please let me know how to get required output using following input
Input : 2008-09-17 10:45:00 PM
Output : 2008-09-17 17:15:00 PM
required output: 1715UTC
from datetime import *
from dateutil import *
from dateutil.tz import tz
utc_zone = tz.gettz('UTC')
local_zone = tz.gettz('Asia/kolkata')
utc_zone = tz.tzutc()
local_zone = tz.tzlocal()
# Convert time string to datetime
local_time = datetime.strptime("2008-09-17 10:45:00 PM", '%Y-%m-%d %I:%M:%S %p')
local_time = local_time.replace(tzinfo=local_zone)
utc_time = local_time.astimezone(utc_zone)
utc_string = utc_time.strftime('%Y-%m-%d %H:%M:%S %p')
print utc_string
See this:
How do I convert local time to UTC in Python?
It shows how to format the time as per your requirements.
How would I convert the result from strptime into an integer value or a value that can be used by date.date()?
convertTOdate = time.strptime('2007-07-18 10:03:19', '%Y-%m-%d %H:%M:%S')
duedate = datetime.datetime(convertTOdate)
A Solution on stackoverflow was to do:
Use time.mktime() to convert the time tuple (in localtime) into seconds since the Epoch, then use datetime.fromtimestamp() to get the datetime object.
from time import mktime
from datetime import datetime
dt = datetime.fromtimestamp(mktime(struct))
I do not want to get the local time as it would not work with my function
I am using Python 2
Thank you
You can use the following approach.
from datetime import datetime
def time_in_seconds(dt):
epoch = datetime.utcfromtimestamp(0)
delta = dt - epoch
return delta.total_seconds()
convertTOdate = datetime.strptime('2007-07-18 10:03:19', '%Y-%m-%d %H:%M:%S')
duedate = time_in_seconds(convertTOdate)
returns 1184752999.0 which is equivalent to 2007-07-18 10:03:19
duedate = datetime.utcfromtimestamp(duedate)
print duedate
Just remember before using the following two:
fromtimestamp give you the date and time in local time and utcfromtimestamp gives you the date and time in UTC.
How to use this same logic without using the re.
#!/usr/bin/env python
#Import the regular expression
import re
print "The task Begins"
print " The Begin time is at 03:00:00"
#Set the beginning time and name it as starttime
starttime="03:00:00"
print "The End time is at 03:59:59"
#Set the ending time and name it as endtime
endtime="03:59:59"
#Specify the time format
time_re = re.compile(r'(\d+:\d+:\d+)')
#Using the condition
with open("abc.log", "r") as fh:
for line in fh.readlines():
match = time_re.search(line)
if match:
matchDate = match.group(1)
if matchDate >= starttime and matchDate <= endtime:
print match.string.strip()
print "The task is completed"
PS: Use the DateTime and Time .
you can use string.find() but it is better to use regular expression.
Import the datetime
from datetime import datetime
import re
Create two datetime object for 12:00:00 and 04:59:59 as dt1 and dt2 respectively
dt1 = datetime.strptime("12:00:00","%H:%M:%S").time()
dt2 = datetime.strptime("04:59:59","%H:%M:%S").time()
time_re = re.compile(r'(\d+:\d+:\d+)')
for line in open("test.log", "r"):
match = time_re.search(line)
if match:
matchdate = match.group(1)
dt_match = datetime.strptime( matchdate, '%H:%M:%S').time()
if dt_match >= dt1 and dt_match <= dt2:
print match.string.strip()
You can use datetime.datetime.now()strftime("%d-%m-%Y") to get date-month-year format if it will help you but I don't understand what you are trying to do because what you are currently doing is perfectly fine.
I am using external api which returns dates (as strings) in a strange format:
2012-09-26T15:44:10.376000 #timestamp
0:00:01.714000 #delta (some time duration)
I want to convert them to this format:
19 Sep 2012 17:02
0:17:34
Is there easy way to do this?
I can convert them in my view or in template
edit -----------------------------------------------------------
I found solution for timestamp:
date_str = '2012-09-26T15:44:10.376000'
date = datetime.strptime(date_str.split('.')[0],'%Y-%m-%dT%H:%M:%S')
str = date.strftime('%m %b %Y %H:%M')
Install dateutil and then:
>>> import dateutil.parser
>>> dt = dateutil.parser.parse('2012-09-26T15:44:10.376000')
>>> dt.strftime('%d %b %Y %H:%M')
'26 Sep 2012 15:44'
For django, you can pass the dt object to your template and use the date filter:
{{ dt|date:"d b Y H:M" }}