I received the datetime in below format
timestamp = '2019-03-18 01:50:00 -0800'
and wanted to convert into datetime in python
i tried but won't able to pick the UTC offset
from datetime import datetime
from datetime import timedelta
timestamp = '2019-03-18 01:50:00 -0800'
date_format = '%Y-%m-%d %H:%M:%S %z'
d_t =datetime.strptime(timestamp,date_format)
Error i get
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/usr/lib/python2.7/_strptime.py", line 324, in _strptime
(bad_directive, format))
ValueError: 'z' is a bad directive in format '%Y-%m-%d %H:%M:%S %z'
how to pick UTC offset in python 2.7?
Just use dateutil
from dateutil import parser
obj = parser.parse('2019-03-18 01:50:00 -0800')
print(obj)
#2019-03-18 01:50:00-08:00
Install pytz library
sudo easy_install --upgrade pytz
Import pytz to code
from datetime import datetime
from pytz import timezone
date_str = "2009-05-05 22:28:15"
datetime_obj = datetime.strptime(date_str, "%Y-%m-%d %H:%M:%S") #parse only date & time
datetime_obj_utc = datetime_obj.replace(tzinfo=timezone('UTC')) #get time zone using pytz
print datetime_obj_utc.strftime("%Y-%m-%d %H:%M:%S %Z%z")
It should help.
Related
I used the %-I format for time, but it throws an error saying
"Traceback (most recent call last):
File "c:\Users\Lenovo\Desktop\VA Project\EDITH.py", line 31, in
timeEve = now.strftime("%-I %M")
ValueError: Invalid format string"
import pyttsx3
import tkinter
import speech_recognition as sr
import datetime
import time
from datetime import date
today = date.today()
now = datetime.datetime.now()
# Textual month, day and year
d8 = today.strftime("%A %B %d, %Y")
time = now.strftime("%H%M")
timeDay = now.strftime("%M")
timeEve = now.strftime("%-I %M") #THIS IS WHERE THE PROBLEM IS WITH THE "%-I"
def askTime():
engine = pyttsx3.init()
engine.setProperty('rate', 170) # Decrease the Speed Rate x2
if int(time)<1200:
engine.say("Good morning!")
engine.say("Today is "+d8)
engine.say("and the time is "+timeDay)
engine.runAndWait()
if int(time)>1200 and int(time)<1600:
engine.say("Good afternoon!")
engine.say("Today is "+d8)
engine.say("and the time is "+timeEve)
engine.runAndWait()
if int(time)>1600:
engine.say("Good evening!")
engine.say("Today is "+d8)
engine.say("and the time is "+timeEve)
engine.runAndWait()
Facing issues while converting date to string,
print(type(from_date))
from_date = datetime.datetime.strptime(from_date, '%Y-%m-%d').date()
My from_date value is in an ini file,
from_date = 2018-01-01
My TraceBack log is,
Traceback (most recent call last):
File "Flexi_DailyToWeekly.py", line 87, in <module>
tuesday = get_data(session,from_keyspace, from_table, to_keyspace, to_table_tuesday, to_table_wednesday, to_table_thursday, to_table_friday, from_date, to_date)
File "Flexi_DailyToWeekly.py", line 11, in get_data
from_date = datetime.datetime.strptime(from_date, '%Y-%m-%d')
TypeError: strptime() argument 1 must be str, not datetime.date'
I've used type(from_date) which returns from_date as a string.
Also tried,
from_date = datetime.datetime.strptime(str(from_date), '%Y-%m-%d').date()
still the same error persists.
Changed from_date as suggested in the answers below,
from_date = "2018-01-01"
The error persisits,
Traceback (most recent call last):
File "Flexi_DailyToWeekly.py", line 82, in <module>
from_date = datetime.datetime.strptime(from_date, '%Y-%m-%d').date()
File "/usr/lib/python3.5/_strptime.py", line 510, in _strptime_datetime
tt, fraction = _strptime(data_string, format)
File "/usr/lib/python3.5/_strptime.py", line 343, in _strptime
(data_string, format))
ValueError: time data '"2018-01-01"' does not match format '%Y-%m-%d'
Replace
from_date = 2018-01-01
to
from_date : 2018-01-01
in ini file
Tested with code :
import configparser
import datetime
config = configparser.ConfigParser()
config.read('Test.ini')
print (config['DEFAULT']['date'])
from_date = config['DEFAULT']['date']
print(type(from_date))
from_date = datetime.datetime.strptime(from_date, '%Y-%m-%d').date()
print (from_date)
and Test.ini is
[DEFAULT]
date : 2018-1-1
output is :
2018-1-1
<class 'str'>
2018-01-01
As per docs, The datetime.strptime() method accepts a date_string as the first argument. So, I tried this:
import datetime
test = datetime.datetime.strptime('2018-01-01', '%Y-%m-%d').date()
print(test)
#datetime.date(2018, 1, 1)
If I do from_date = 2018-01-01, I get an invalid token error for the type of from_date:
from_date = 2018-01-01
print(type(from_date))
File "<ipython-input-7-9e5449277912>", line 2
from_date = 2018-01-01
^
SyntaxError: invalid token
This means that from_date must be a string. You could use from_date = '2018-01-01' and that would work. If I check the type of from_date now, I will get a type of class string:
from_date = '2018-01-01'
print(type(from_date))
#<class 'str'>
But when I look at the first Traceback log, it raises a TypeError. This means that the value stored in from_date is of type datetime.date. Consider the following:
import datetime
from_date = datetime.date(2018, 1, 1)
test = datetime.datetime.strptime(str(from_date), '%Y-%m-%d').date()
print(test)
#2018-01-01
I have a python script
import urllib2
from bs4 import BeautifulSoup
import requests
import csv
from datetime import datetime
from datetime import date
from datetime import timedelta
def generateDateList(date,month,year):
today = date(year, month, date)
arrDates = []
for i in range(0,5):
arrDates.append(datetime.strftime(today + timedelta(days=i),"%d-%m-%y"))
return arrDates
print generateDateList(4,12,2017)
But i get this error-
Traceback (most recent call last):
File "test.py", line 17, in <module>
print generateDateList(4,12,2017)
File "test.py", line 11, in generateDateList
today = date(year, month, date)
TypeError: 'int' object is not callable
Why is it failing? I substituted the function with values and it worked. Should i convert the function inputs to integer again?
This line - def generateDateList(date,month,year):
The name of the first argument date shadows the name date imported at the top. You need to rename the argument to something like day inside your function.
As written, date is actually an integer you pass to the function, and calling it results in an error you are seeing.
Two options.
Option No.1 (import datetime):
import datetime
def generateDateList(date, month, year):
today = datetime.date(year, month, date)
arrDates = []
for i in range(0,5):
arrDates.append(datetime.datetime.strftime(today + datetime.timedelta(days=i),"%d-%m-%y"))
return arrDates
print generateDateList(4, 12, 2017)
Option No.2 (rename date parameter to day):
from datetime import datetime
from datetime import date
from datetime import timedelta
def generateDateList(day,month,year):
today = date(year, month, day)
arrDates = []
for i in range(0,5):
arrDates.append(datetime.strftime(today + timedelta(days=i),"%d-%m-%y"))
return arrDates
print generateDateList(4,12,2017)
The problem is the fact you have a parameter with the same name of the date() function.
I am new at Python. I was trying to play with time and date objects. I wrote a simple test program to parse a string into a specific time format. But its throwing a ValueError. Can you please help me out here?
Here is the code:
import time
testDate = "Tuesday, Febuary 23 2011 12:00:00 UTC"
today = time.strptime(testDate,"%A, %B %d %Y %H:%M:%S %Z")
print today
and the error:
Traceback (most recent call last):
File "D:\Python\PythonTest\src\helloWorld.py", line 3, in <module>
today = time.strptime(testDate,"%A, %B %d %Y %H:%M:%S %Z")
File "C:\Python27\Lib\_strptime.py", line 467, in _strptime_time
return _strptime(data_string, format)[0]
File "C:\Python27\Lib\_strptime.py", line 325, in _strptime
(data_string, format))
ValueError: time data 'Tuesday, Febuary 23 2011 12:00:00 UTC' does not match format '%A, %B %d %Y %H:%M:%S %Z'
You had February misspelled. Your code works.
import time
testDate = "Tuesday, February 23 2011 12:00:00 UTC"
today = time.strptime(testDate,"%A, %B %d %Y %H:%M:%S %Z")
print today
Very simple: you spelled "February" wrong:
import time
testDate = "Tuesday, February 23 2011 12:00:00 UTC"
today = time.strptime(testDate,"%A, %B %d %Y %H:%M:%S %Z")
print today
Originally, you had "February" spelled as "Febuary". Works fine once that is fixed.
I cannot understand why this is failing, can someone please explain:
import datetime
def test(timestamp):
xt = datetime(2013, 4,4)
dt = datetime.strptime(timestamp, '%d/%m/%Y %H:%M:%S')
print (xt,dt)
test('04/04/2013 08:37:20')
The error is:
Traceback (most recent call last):
File "", line 12, in
File "", line 5, in test
TypeError: 'module' object is not callable
It seems to work ok with from datetime import datetime instead. I can't understand what the difference is.
Thanks.
Because in the datetime module, there is a datetime() function, but you didn't call it ( you instead tried to call the module, that's why you got a TypeError: 'module' object is not callable).
import datetime
def test(timestamp):
xt = datetime(2013, 4,4) # Problem is this line.
dt = datetime.strptime(timestamp, '%d/%m/%Y %H:%M:%S')
print (xt,dt)
test('04/04/2013 08:37:20')
To fix the line, change it to:
xt = datetime.datetime(2013,4,4)
The reason from datetime import datetime worked was because you imported the specific function, and so you wouldn't need to do datetime.datetime().
datetime is both a module AND a class in that module. In your example you need datetime.datetime.
The
xt = datetime(2013, 4,4)
should be
xt = datetime.datetime(2013, 4,4)
Here, datetime is the name of the module. The full name of the class is datetime.datetime.
datetime is the datetime module, datetime.datetime is the datetime type:
import datetime
def test(timestamp):
xt = datetime.datetime(2013, 4,4)
dt = datetime.datetime.strptime(timestamp, '%d/%m/%Y %H:%M:%S')
print (xt,dt)
Here datetime can refer to the module or the class within the module so you have to disambiguate
import datetime
def test(timestamp):
xt = datetime.datetime(2013, 4,4)
dt = datetime.datetime.strptime(timestamp, '%d/%m/%Y %H:%M:%S')
print (xt,dt)
test('04/04/2013 08:37:20')
gives the following output:
(datetime.datetime(2013, 4, 4, 0, 0), datetime.datetime(2013, 4, 4, 8, 37, 20))