1642662494
Returns true
if component is just mounted (on first render) and false
otherwise.
import * as React from 'react';
import { useFirstMountState } from 'react-use';
const Demo = () => {
const isFirstMount = useFirstMountState();
const update = useUpdate();
return (
<div>
<span>This component is just mounted: {isFirstMount ? 'YES' : 'NO'}</span>
<br />
<button onClick={update}>re-render</button>
</div>
);
};
const isFirstMount: boolean = useFirstMountState();
Original article source at https://github.com
#react #hook #reacthook #javascript #programming #developer
1659694200
public_activity
provides easy activity tracking for your ActiveRecord, Mongoid 3 and MongoMapper models in Rails 3 and 4.
Simply put: it can record what happens in your application and gives you the ability to present those recorded activities to users - in a similar way to how GitHub does it.
You probably don't want to read the docs for this unreleased version 2.0.
For the stable 1.5.X
readme see: https://github.com/chaps-io/public_activity/blob/1-5-stable/README.md
Here is a simple example showing what this gem is about:
Ryan Bates made a great screencast describing how to integrate Public Activity.
A great step-by-step guide on implementing activity feeds using public_activity by Ilya Bodrov.
You can see an actual application using this gem here: http://public-activity-example.herokuapp.com/feed
The source code of the demo is hosted here: https://github.com/pokonski/activity_blog
You can install public_activity
as you would any other gem:
gem install public_activity
or in your Gemfile:
gem 'public_activity'
By default public_activity
uses Active Record. If you want to use Mongoid or MongoMapper as your backend, create an initializer file in your Rails application with the corresponding code inside:
For Mongoid:
# config/initializers/public_activity.rb
PublicActivity.configure do |config|
config.orm = :mongoid
end
For MongoMapper:
# config/initializers/public_activity.rb
PublicActivity.configure do |config|
config.orm = :mongo_mapper
end
(ActiveRecord only) Create migration for activities and migrate the database (in your Rails project):
rails g public_activity:migration
rake db:migrate
Include PublicActivity::Model
and add tracked
to the model you want to keep track of:
For ActiveRecord:
class Article < ActiveRecord::Base
include PublicActivity::Model
tracked
end
For Mongoid:
class Article
include Mongoid::Document
include PublicActivity::Model
tracked
end
For MongoMapper:
class Article
include MongoMapper::Document
include PublicActivity::Model
tracked
end
And now, by default create/update/destroy activities are recorded in activities table. This is all you need to start recording activities for basic CRUD actions.
Optional: If you don't need #tracked
but still want the comfort of #create_activity
, you can include only the lightweight Common
module instead of Model
.
You can trigger custom activities by setting all your required parameters and triggering create_activity
on the tracked model, like this:
@article.create_activity key: 'article.commented_on', owner: current_user
See this entry http://rubydoc.info/gems/public_activity/PublicActivity/Common:create_activity for more details.
To display them you simply query the PublicActivity::Activity
model:
# notifications_controller.rb
def index
@activities = PublicActivity::Activity.all
end
And in your views:
<%= render_activities(@activities) %>
Note: render_activities
is an alias for render_activity
and does the same.
You can also pass options to both activity#render
and #render_activity
methods, which are passed deeper to the internally used render_partial
method. A useful example would be to render activities wrapped in layout, which shares common elements of an activity, like a timestamp, owner's avatar etc:
<%= render_activities(@activities, layout: :activity) %>
The activity will be wrapped with the app/views/layouts/_activity.html.erb
layout, in the above example.
Important: please note that layouts for activities are also partials. Hence the _
prefix.
Sometimes, it's desirable to pass additional local variables to partials. It can be done this way:
<%= render_activity(@activity, locals: {friends: current_user.friends}) %>
Note: Before 1.4.0, one could pass variables directly to the options hash for #render_activity
and access it from activity parameters. This functionality is retained in 1.4.0 and later, but the :locals
method is preferred, since it prevents bugs from shadowing variables from activity parameters in the database.
public_activity
looks for views in app/views/public_activity
.
For example, if you have an activity with :key
set to "activity.user.changed_avatar"
, the gem will look for a partial in app/views/public_activity/user/_changed_avatar.html.(|erb|haml|slim|something_else)
.
Hint: the "activity."
prefix in :key
is completely optional and kept for backwards compatibility, you can skip it in new projects.
If you would like to fallback to a partial, you can utilize the fallback
parameter to specify the path of a partial to use when one is missing:
<%= render_activity(@activity, fallback: 'default') %>
When used in this manner, if a partial with the specified :key
cannot be located it will use the partial defined in the fallback
instead. In the example above this would resolve to public_activity/_default.html.(|erb|haml|slim|something_else)
.
If a view file does not exist then ActionView::MisingTemplate will be raised. If you wish to fallback to the old behaviour and use an i18n based translation in this situation you can specify a :fallback
parameter of text
to fallback to this mechanism like such:
<%= render_activity(@activity, fallback: :text) %>
Translations are used by the #text
method, to which you can pass additional options in form of a hash. #render
method uses translations when view templates have not been provided. You can render pure i18n strings by passing {display: :i18n}
to #render_activity
or #render
.
Translations should be put in your locale .yml
files. To render pure strings from I18n Example structure:
activity:
article:
create: 'Article has been created'
update: 'Someone has edited the article'
destroy: 'Some user removed an article!'
This structure is valid for activities with keys "activity.article.create"
or "article.create"
. As mentioned before, "activity."
part of the key is optional.
For RSpec you can first disable public_activity
and add require helper methods in the rails_helper.rb
with:
#rails_helper.rb
require 'public_activity/testing'
PublicActivity.enabled = false
In your specs you can then blockwise decide whether to turn public_activity
on or off.
# file_spec.rb
PublicActivity.with_tracking do
# your test code goes here
end
PublicActivity.without_tracking do
# your test code goes here
end
For more documentation go here
You can set up a default value for :owner
by doing this:
PublicActivity::StoreController
in your ApplicationController
like this:class ApplicationController < ActionController::Base
include PublicActivity::StoreController
end
:owner
attribute for tracked
class method in your desired model. For example:class Article < ActiveRecord::Base
tracked owner: Proc.new{ |controller, model| controller.current_user }
end
Note: current_user
applies to Devise, if you are using a different authentication gem or your own code, change the current_user
to a method you use.
If you need to disable tracking temporarily, for example in tests or db/seeds.rb
then you can use PublicActivity.enabled=
attribute like below:
# Disable p_a globally
PublicActivity.enabled = false
# Perform some operations that would normally be tracked by p_a:
Article.create(title: 'New article')
# Switch it back on
PublicActivity.enabled = true
You can also disable public_activity for a specific class:
# Disable p_a for Article class
Article.public_activity_off
# p_a will not do anything here:
@article = Article.create(title: 'New article')
# But will be enabled for other classes:
# (creation of the comment will be recorded if you are tracking the Comment class)
@article.comments.create(body: 'some comment!')
# Enable it again for Article:
Article.public_activity_on
Besides standard, automatic activities created on CRUD actions on your model (deactivatable), you can post your own activities that can be triggered without modifying the tracked model. There are a few ways to do this, as PublicActivity gives three tiers of options to be set.
Because every activity needs a key (otherwise: NoKeyProvided
is raised), the shortest and minimal way to post an activity is:
@user.create_activity :mood_changed
# the key of the action will be user.mood_changed
@user.create_activity action: :mood_changed # this is exactly the same as above
Besides assigning your key (which is obvious from the code), it will take global options from User class (given in #tracked
method during class definition) and overwrite them with instance options (set on @user
by #activity
method). You can read more about options and how PublicActivity inherits them for you here.
Note the action parameter builds the key like this: "#{model_name}.#{action}"
. You can read further on options for #create_activity
here.
To provide more options, you can do:
@user.create_activity action: 'poke', parameters: {reason: 'bored'}, recipient: @friend, owner: current_user
In this example, we have provided all the things we could for a standard Activity.
Besides the few fields that every Activity has (key
, owner
, recipient
, trackable
, parameters
), you can also set custom fields. This could be very beneficial, as parameters
are a serialized hash, which cannot be queried easily from the database. That being said, use custom fields when you know that you will set them very often and search by them (don't forget database indexes :) ).
owner
and recipient
based on associationsclass Comment < ActiveRecord::Base
include PublicActivity::Model
tracked owner: :commenter, recipient: :commentee
belongs_to :commenter, :class_name => "User"
belongs_to :commentee, :class_name => "User"
end
class Post < ActiveRecord::Base
include PublicActivity::Model
tracked only: [:update], parameters: :tracked_values
def tracked_values
{}.tap do |hash|
hash[:tags] = tags if tags_changed?
end
end
end
Skip this step if you are using ActiveRecord in Rails 4 or Mongoid
The first step is similar in every ORM available (except mongoid):
PublicActivity::Activity.class_eval do
attr_accessible :custom_field
end
place this code under config/initializers/public_activity.rb
, you have to create it first.
To be able to assign to that field, we need to move it to the mass assignment sanitizer's whitelist.
If you're using ActiveRecord, you will also need to provide a migration to add the actual field to the Activity
. Taken from our tests:
class AddCustomFieldToActivities < ActiveRecord::Migration
def change
change_table :activities do |t|
t.string :custom_field
end
end
end
Assigning is done by the same methods that you use for normal parameters: #tracked
, #create_activity
. You can just pass the name of your custom variable and assign its value. Even better, you can pass it to #tracked
to tell us how to harvest your data for custom fields so we can do that for you.
class Article < ActiveRecord::Base
include PublicActivity::Model
tracked custom_field: proc {|controller, model| controller.some_helper }
end
If you need help with using public_activity please visit our discussion group and ask a question there:
https://groups.google.com/forum/?fromgroups#!forum/public-activity
Please do not ask general questions in the Github Issues.
Author: public-activity
Source code: https://github.com/public-activity/public_activity
License: MIT license
1657081614
In this article, We will show how we can use python to automate Excel . A useful Python library is Openpyxl which we will learn to do Excel Automation
Openpyxl is a Python library that is used to read from an Excel file or write to an Excel file. Data scientists use Openpyxl for data analysis, data copying, data mining, drawing charts, styling sheets, adding formulas, and more.
Workbook: A spreadsheet is represented as a workbook in openpyxl. A workbook consists of one or more sheets.
Sheet: A sheet is a single page composed of cells for organizing data.
Cell: The intersection of a row and a column is called a cell. Usually represented by A1, B5, etc.
Row: A row is a horizontal line represented by a number (1,2, etc.).
Column: A column is a vertical line represented by a capital letter (A, B, etc.).
Openpyxl can be installed using the pip command and it is recommended to install it in a virtual environment.
pip install openpyxl
We start by creating a new spreadsheet, which is called a workbook in Openpyxl. We import the workbook module from Openpyxl and use the function Workbook()
which creates a new workbook.
from openpyxl
import Workbook
#creates a new workbook
wb = Workbook()
#Gets the first active worksheet
ws = wb.active
#creating new worksheets by using the create_sheet method
ws1 = wb.create_sheet("sheet1", 0) #inserts at first position
ws2 = wb.create_sheet("sheet2") #inserts at last position
ws3 = wb.create_sheet("sheet3", -1) #inserts at penultimate position
#Renaming the sheet
ws.title = "Example"
#save the workbook
wb.save(filename = "example.xlsx")
We load the file using the function load_Workbook()
which takes the filename as an argument. The file must be saved in the same working directory.
#loading a workbook
wb = openpyxl.load_workbook("example.xlsx")
#getting sheet names
wb.sheetnames
result = ['sheet1', 'Sheet', 'sheet3', 'sheet2']
#getting a particular sheet
sheet1 = wb["sheet2"]
#getting sheet title
sheet1.title
result = 'sheet2'
#Getting the active sheet
sheetactive = wb.active
result = 'sheet1'
#get a cell from the sheet
sheet1["A1"] <
Cell 'Sheet1'.A1 >
#get the cell value
ws["A1"].value 'Segment'
#accessing cell using row and column and assigning a value
d = ws.cell(row = 4, column = 2, value = 10)
d.value
10
#looping through each row and column
for x in range(1, 5):
for y in range(1, 5):
print(x, y, ws.cell(row = x, column = y)
.value)
#getting the highest row number
ws.max_row
701
#getting the highest column number
ws.max_column
19
There are two functions for iterating through rows and columns.
Iter_rows() => returns the rows
Iter_cols() => returns the columns {
min_row = 4, max_row = 5, min_col = 2, max_col = 5
} => This can be used to set the boundaries
for any iteration.
Example:
#iterating rows
for row in ws.iter_rows(min_row = 2, max_col = 3, max_row = 3):
for cell in row:
print(cell) <
Cell 'Sheet1'.A2 >
<
Cell 'Sheet1'.B2 >
<
Cell 'Sheet1'.C2 >
<
Cell 'Sheet1'.A3 >
<
Cell 'Sheet1'.B3 >
<
Cell 'Sheet1'.C3 >
#iterating columns
for col in ws.iter_cols(min_row = 2, max_col = 3, max_row = 3):
for cell in col:
print(cell) <
Cell 'Sheet1'.A2 >
<
Cell 'Sheet1'.A3 >
<
Cell 'Sheet1'.B2 >
<
Cell 'Sheet1'.B3 >
<
Cell 'Sheet1'.C2 >
<
Cell 'Sheet1'.C3 >
To get all the rows of the worksheet we use the method worksheet.rows and to get all the columns of the worksheet we use the method worksheet.columns. Similarly, to iterate only through the values we use the method worksheet.values.
Example:
for row in ws.values:
for value in row:
print(value)
Writing to a workbook can be done in many ways such as adding a formula, adding charts, images, updating cell values, inserting rows and columns, etc… We will discuss each of these with an example.
#creates a new workbook
wb = openpyxl.Workbook()
#saving the workbook
wb.save("new.xlsx")
#creating a new sheet
ws1 = wb.create_sheet(title = "sheet 2")
#creating a new sheet at index 0
ws2 = wb.create_sheet(index = 0, title = "sheet 0")
#checking the sheet names
wb.sheetnames['sheet 0', 'Sheet', 'sheet 2']
#deleting a sheet
del wb['sheet 0']
#checking sheetnames
wb.sheetnames['Sheet', 'sheet 2']
#checking the sheet value
ws['B2'].value
null
#adding value to cell
ws['B2'] = 367
#checking value
ws['B2'].value
367
We often require formulas to be included in our Excel datasheet. We can easily add formulas using the Openpyxl module just like you add values to a cell.
For example:
import openpyxl
from openpyxl
import Workbook
wb = openpyxl.load_workbook("new1.xlsx")
ws = wb['Sheet']
ws['A9'] = '=SUM(A2:A8)'
wb.save("new2.xlsx")
The above program will add the formula (=SUM(A2:A8)) in cell A9. The result will be as below.
Two or more cells can be merged to a rectangular area using the method merge_cells(), and similarly, they can be unmerged using the method unmerge_cells().
For example:
Merge cells
#merge cells B2 to C9
ws.merge_cells('B2:C9')
ws['B2'] = "Merged cells"
Adding the above code to the previous example will merge cells as below.
#unmerge cells B2 to C9
ws.unmerge_cells('B2:C9')
The above code will unmerge cells from B2 to C9.
To insert an image we import the image function from the module openpyxl.drawing.image. We then load our image and add it to the cell as shown in the below example.
Example:
import openpyxl
from openpyxl
import Workbook
from openpyxl.drawing.image
import Image
wb = openpyxl.load_workbook("new1.xlsx")
ws = wb['Sheet']
#loading the image(should be in same folder)
img = Image('logo.png')
ws['A1'] = "Adding image"
#adjusting size
img.height = 130
img.width = 200
#adding img to cell A3
ws.add_image(img, 'A3')
wb.save("new2.xlsx")
Result:
Charts are essential to show a visualization of data. We can create charts from Excel data using the Openpyxl module chart. Different forms of charts such as line charts, bar charts, 3D line charts, etc., can be created. We need to create a reference that contains the data to be used for the chart, which is nothing but a selection of cells (rows and columns). I am using sample data to create a 3D bar chart in the below example:
Example
import openpyxl
from openpyxl
import Workbook
from openpyxl.chart
import BarChart3D, Reference, series
wb = openpyxl.load_workbook("example.xlsx")
ws = wb.active
values = Reference(ws, min_col = 3, min_row = 2, max_col = 3, max_row = 40)
chart = BarChart3D()
chart.add_data(values)
ws.add_chart(chart, "E3")
wb.save("MyChart.xlsx")
Result
Welcome to another video! In this video, We will cover how we can use python to automate Excel. I'll be going over everything from creating workbooks to accessing individual cells and stylizing cells. There is a ton of things that you can do with Excel but I'll just be covering the core/base things in OpenPyXl.
⭐️ Timestamps ⭐️
00:00 | Introduction
02:14 | Installing openpyxl
03:19 | Testing Installation
04:25 | Loading an Existing Workbook
06:46 | Accessing Worksheets
07:37 | Accessing Cell Values
08:58 | Saving Workbooks
09:52 | Creating, Listing and Changing Sheets
11:50 | Creating a New Workbook
12:39 | Adding/Appending Rows
14:26 | Accessing Multiple Cells
20:46 | Merging Cells
22:27 | Inserting and Deleting Rows
23:35 | Inserting and Deleting Columns
24:48 | Copying and Moving Cells
26:06 | Practical Example, Formulas & Cell Styling
📄 Resources 📄
OpenPyXL Docs: https://openpyxl.readthedocs.io/en/stable/
Code Written in This Tutorial: https://github.com/techwithtim/ExcelPythonTutorial
Subscribe: https://www.youtube.com/c/TechWithTim/featured
1627019580
In this small post we will see how to get current url in laravel, if you want to get current page url in laravel then we can use many method such type current(), full(), request(), url().
Here i will give you all example to get current page url in laravel, in this example i have used helper and function as well as so let’s start example of how to get current url id in laravel.
#how to get current url in laravel #laravel get current url #get current page url in laravel #find current url in laravel #get full url in laravel #how to get current url id in laravel
1599921480
I understand your frustration and I have some good news and bad news.
While there are a lot of different “first” methodologies out there, some are very similar and have just matured just as our technology stack has.
Here is the first stack I recommend looking at when you are starting a new project:
Know the high-level, big-picture view of what you are building. Define the problem you are solving and the requirements to solve it. Are you going to need a Mobile app? Website? Something else?
Have the foresight to realize that whatever you think you will need, it will change in the future. I am not saying design for every possible outcome but use wisdom and listen to your experts.
API First means you think of APIs as being in the center of your little universe. APIs run the world and they are the core to every (well, almost every) technical product you put on a user’s phone, computer, watch, tv, etc. If you break this first, you will find yourself in a world of hurt.
Part of this First
is the knowledge that you better focus on your API first, before you start looking at your web page, mobile app, etc. If you try to build your mobile app first and then go back and try to create an API that matches the particular needs of that one app, the above world of hurt applies.
Not only this but having a working API will make design/implementation of your mobile app or website MUCH easier!
Another important point to remember. There will most likely be another client that needs what this API is handing out so take that into consideration as well.
I’ve grouped these next two together. Now I know I am going to take a lot of flak for this but hear me out.
I agree that you should always design your API first and not just dig into building it, However, code is a legitimate design tool, in the right hands. Not everyone wants to use some WYSIWYG tool that may or may not take add eons to your learning curve and timetable. Good Architects (and I mean GOOD!) can design out an API in a fraction of the time it takes to use some API design tools. I am NOT saying everyone should do this but don’t rule out Code-First because it has the word “Code” in it.
You have to know where to stop though.
Designing your API with code means you are doing design-only. You still have to work with the technical and non-technical members of your team to ensure that your API solves your business problem and is the best solution. If you can’t translate your code-design into some visual format that everyone can see and understand, DON’T use code.
#devops #integration #code first #design first #api first #api
1675498447
Convert a string to a
datetime
object in Python using thestrptime()
method. Using the datetime.strptime() method to convert strings to datetime objects.
Python offers a variety of built-in modules that you can include in your program.
A module is a Python file containing the necessary code to execute an individual functionality. This file is imported into your application to help you perform a specific task.
One of those modules is the datetime
module for working with and manipulating times and dates.
The datetime
module includes the datetime
class, which in turn provides the strptime()
class method. The strptime()
method creates a datetime object from a string representation of a corresponding date and time.
In this article, you will learn how to use the datetime.strptime()
method to convert strings to datetime objects.
Let's get into it!
datetime.strptime()
Method in Python? A datetime.strptime()
Syntax BreakdownThe general syntax for the datetime.strptime()
method looks something similar to the following:
datetime.strptime(date_string, format_code)
Let's break it down.
Firstly, datetime
is the class name.
Then, strptime()
is the method name. The method accepts two required string arguments.
date_string
– the string representation of the date you want to convert to a datetime object.format_code
– a specific format to help you convert the string to a datetime object.Here is a brief list of some of the most commonly used code formats you may come across:
%d
- the day of the month as a zero-padded decimal number such as 28
.%a
- a day's abbreviated name, such as Sun
.%A
- a day's full name, such as Sunday
.%m
- the month as a zero-padded decimal number, such as 01
.%b
- month's abbreviated name, such as Jan
.%B
- the month's full name, such as January
.%y
- the year without century, such as 23
.%Y
- the year with century, such as 2023
.%H
- the hours of the day in a 24-hour format, such as 08
.%I
- the hours of the day in a 12-hour format.%M
- the minutes in an hour, such as 20
.%S
- the seconds in a minute, such as 00
.To view a table that shows all of the format codes for datetime.strptime()
, refer to the Python documentation.
datetime.strptime()
Method in Python? How to Convert a String to a Datetime Object in PythonLet's say I have the following string that represents a date and time:
28/01/23 08:20:00
And I want to get the following output:
2023-01-28 08:20:00
How would I achieve that?
Let's take a look at the code below:
# import the datetime class from the datetime module
from datetime import datetime
date_time_str = "28/01/23 08:20:00"
# check data type of date_time_str
print(type(date_time_str))
# output
# <class 'str'>
First, I import the datetime
module with the from datetime import datetime
statement.
Then, I store the string I want to convert to a datetime object in a variable named date_time_str
and check its type using the type()
function. The output indicates that it is a string.
Now, let's convert the string to a datetime object using the strptime()
method of the datetime
class and check the data type:
from datetime import datetime
date_time_str = "28/01/23 08:20:00"
date_time_object = datetime.strptime(date_time_str, "%d/%m/%y %H:%M:%S")
print(date_time_object)
# check date_time_object_type
print(type(date_time_object))
# output
# 2023-01-28 08:20:00
# <class 'datetime.datetime'>
The format codes for the string 28/01/23 08:20:00
are %d/%m/%y %H:%M:%S
.
The format codes %d,%m,%y,%H,%M,%S
represent the day of the month, the month as a zero-padded decimal number, the year without century, the hour of the day, the minutes of the day and the seconds of the day, respectively.
Now, let's change the initial string a bit.
Let's change it from 28/01/23
to 28 January 2023
and check the data type of date_time_str
:
from datetime import datetime
date_time_str = "28 January 2023 08:20:00"
#check data type
print(type(date_time_str))
# output
# <class 'str'>
Now, let's convert date_time_str
to a datetime object – keep in mind that because the string is different, you must also change the format codes:
from datetime import datetime
date_time_str = "28 January 2023 08:20:00"
date_object = datetime.strptime(date_time_str, "%d %B %Y %H:%M:%S")
print(date_object)
#check data type
print(type(date_object))
# output
# 2023-01-28 08:20:00
# <class 'datetime.datetime'>
The format codes for the string 28 January 2023 08:20:00
are %d %B %Y %H:%M:%S
.
Because I changed the month of January from its zero-padded decimal number representation, 01
, to its full name, January
, I also needed to change its format code – from %m
to %B
.
datetime.date()
Object in PythonWhat if you only want to convert the date but not the time from a string?
You may only want to convert only the 28/01/23
part of the 28/01/23 08:20:00
string to an object.
To convert a string to a date object, you will use the strptime()
method like you saw in the previous section, but you will also use the datetime.date()
method to extract only the date.
from datetime import datetime
date_time_str = "28 January 2023 08:20:00"
date_object = datetime.strptime(date_time_str, "%d %B %Y %H:%M:%S").date()
print(date_object)
#check data type
print(type(date_object))
# output
# 2023-01-28
# <class 'datetime.date'>
datetime.time()
Object in PythonAnd to convert only the time part,08:20:00
from the 28/01/23 08:20:00
string, you would use the datetime.time()
method to extract only the time:
from datetime import datetime
date_time_str = "28 January 2023 08:20:00"
date_object = datetime.strptime(date_time_str, "%d %B %Y %H:%M:%S").time()
print(date_object)
print(type(date_object))
# output
# 08:20:00
# <class 'datetime.time'>
ValueError
Get Raised When Using datetime.strptime()
in Python?Something to keep in mind is that the string you pass as an argument to the strptime()
method needs to have a specific format – not any string gets converted into a datetime object.
Specifically, the year, month, and day in the string must match the format code.
For example, the format code for the month in the string 28/01/23
must be %m
, which represents the month as a zero-padded decimal number.
What happens when I use the format code %B
instead?
from datetime import datetime
date_time_str = "28/01/23 08:20:00"
date_time_object = datetime.strptime(date_time_str, "%d/%B/%y %H:%M:%S")
print(date_time_object)
# output
# raise ValueError("time data %r does not match format %r" %
# ValueError: time data '28/01/23 08:20:00' does not match format '%d/%B/%y # %H:%M:%S'
I get a ValueError
!
The %B
format code represents the month's full name, such as January
, and not 01
.
So, if the string passed to strptime()
does not match the format specified, a ValueError
gets raised.
To help with this, you can test and handle the error by using a try-except
block, like so:
from datetime import datetime
date_time_str = "28/01/23 08:20:00"
try:
date_time_object = datetime.strptime(date_time_str, "%d/%B/%y %H:%M:%S")
except ValueError as error:
print('A ValueError is raised because :', error)
# output
# A ValueError is raised because : time data '28/01/23 08:20:00' does not # match format '%d/%B/%y %H:%M:%S'
Hopefully, this article helped you understand how to convert a string to a datetime object in Python using the strptime()
method.
Thank you for reading, and happy coding!
Original article source at https://www.freecodecamp.org
#python